0

How to determine end of file?

FILE* cfl;
if ((cfl=fopen(csv, "r")) == NULL) {
    printf("Cannot open file for read.\r\n");
    exit(1);
}
while (!feof(cfl)) {
    int i = 0;
    char* buf = (char*)malloc(sizeof(char));
    while ((buf[i] = fgetc(cfl)) != '\n') {
        i++;
        buf = (char*)realloc(buf, sizeof(char)*(i+1));
        printf("=%d= ", i);
    }
    buf[i] = '\0';
    printf("+%d+ ", i);
    printf("%s\r\n", buf);
   free(buf);
}

fclose(cfl);

Everything works correctly to the last line. Since the file ends after the last line break, the program loops in while ((buf[i] = fgetc(cfl)) != '\n') {...}

I could interrupt the cycle after checking whether "i" does not exceed some large value, but it will be wrong. How to correctly determine the end of the file and why feof does not work in this case?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Irbis
  • 51
  • 9

1 Answers1

7

The fgetc function returns an int, and the value will be EOF at end of file. This is the typical approach:

int c;
while ((c = fgetc(cfl)) != EOF) {
    ...
}
Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415