Reputation: 1767
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?
Upvotes: 0
Views: 361
Reputation: 6730
You need to close your file after you're done with the reading in the while loop.
void list() {
FILE *todoFile;
todoFile = fopen("./todo.txt", "r");
char line[4096];
if (todoFile != NULL) {
while (fgets(line, sizeof line, todoFile)) {
printf("%s", line);
}
fclose(todoFile);
} else {
printf("ERROR");
}
}
Upvotes: 0