Hi,
I'm using fgets() to read lines of text file and display them. The fgets() is in an infinite loop. The problem occurs when I remove lines from text file while program is running. The lines count is correct, but the program display the old content of the file up to the new lines count.
This is the output of the program:
Lines count: 12
123
456
789
abc
def
ghi
jkl
mno
pqr
stu
vwx
yz0
<<< At this point, I open the text file and remove "pqr" line, save it, and close the file.
Lines count: 11 // Notice that program has correct line counts
123
456
789
abc
def
ghi
jkl
mno
pqr << "pqr" is still here
stu
vwx
<< but "yz0" is disappear
// One more iteration
Lines count: 11 // Notice that program has correct line counts
123
456
789
abc
def
ghi
jkl
mno
pqr << "pqr" is still here
stu
vwx
I tried to google about using fgets() while file is updated, but no luck. The following is the code.
I'm sorry for my bad English. I'm trying my best to explain the problem.
Any help would be really appreciated.
Thanks in advance,
Pat
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
FILE *fp;
char list[2000][20];
int count;
int i, j, k;
for (;;) {
count = 0;
j = 0;
fp = fopen(argv[1], "r");
while (fgets(list[i], 20, fp) != NULL) {
i++;
count++;
}
fclose(fp);
printf("Lines count: %i\n", count);
for (i = 0; i < count; i++) {
for (j = 0; j < strlen(list[i]); j++)
if ((int)list[i][j] == 13)
list[i][j] = '\0';
printf("%s\n", list[i]);
sleep(1);
}
printf("\n");
}
exit(0);
}