I have a file named todo.txt and I have a function that will list every line in the file:
void list() {
FILE *todoFile;
todoFile = fopen("./todo.txt", "r");
char line[4096];
int len;
if (todoFile != NULL) {
while (fgets(line, sizeof line, todoFile)) {
len = strlen(line);
if (len && (line[len - 1] != '\n')) {
printf("%s", line);
}
printf("%s", line);
fclose(todoFile);
}
} else {
printf("ERROR");
}
}
todo.txt contents is:
* foo!
* hello
* FP!
but when I use the list() function only the first line is printed:
* foo!
Any ideas?
You can’t call
fgets()on a closed file.