0

I need some help to rewrite the feof while loop to a for loop in c.

I have two variables n and m.

Variable n is the size of the array / 1023 in rows and m is columns that are 1023 in size.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(){
int n, m;
int *A;
FILE* inputFile;
inputFile = fopen("Input.dat", "r");
        
if(inputFile == NULL){
    printf("An error occured while reading File\n");
    exit(0);
}

else{
    fscanf(inputFile,"%d", &n);
    fscanf(inputFile,"%d", &m);
}

A = (int*)malloc((n*m) * sizeof(int));

if(A == NULL) {
    printf("An error occured while allocating");
    exit(0);
}

int i = 0;
//How can I rewrite this while loop to a for loop in c programming
while(!feof(inputFile)) {
    fscanf(inputFile, "%d", &A[i]);
    i++;
}   

for(int i=0; i<n; i++){
    printf("\n");
    for(int j=0; j<m; j++){
        printf("%d", A[i * m + j]);
    }
}

return 0;
}
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
  • 8
    [Why is “while( !feof(file) )” always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feoffile-always-wrong) should help you understand both why it's wrong, and how to fix it. – Some programmer dude Sep 12 '22 at 13:43
  • Do _not_ write `while (!feof(inputFile))`, it [does not what you intend to do](https://josephmansfield.uk/articles/dont-condition-input-on-eof.html). See also [this](https://latedev.wordpress.com/2012/12/04/all-about-eof/) blog entry. – andreee Sep 12 '22 at 13:43
  • 1
    Use the return value from `fscanf` to control the loop, *and* the value of `i`. So `while(i < n*m && fscanf(inputFile, "%d", &A[i]) == 1) { i++;}` – Weather Vane Sep 12 '22 at 13:43
  • @WeatherVane Should I use return 1 here? – Mohammed Ghazwan Almilhim Sep 12 '22 at 13:46
  • Just where? I don't understand that question. Why should you `return 1` in that loop? – Weather Vane Sep 12 '22 at 13:48
  • 3
    On a very different note: In C you [don't have to (and really shouldn't) cast the result of `malloc`](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc/605858). – Some programmer dude Sep 12 '22 at 13:53

0 Answers0