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?