am using fgets() to read lines from a text file.
the file is being updated after a few seconds.

i want to read and process the last appended line at the end of the file.

i tried the following:

while(true){ //infinite loop

    process line.


plz help.

Something like this (untested)

while ( 1 ) {
  while ( fgets(line,size,fp)!=NULL) {
    // process lines
  clearerr( fp );  // reset end of file flag
  sleep( 1 );  // wait for more lines to arrive

i tried it. its not working.

does fgets() gets aware when a file is updated ?

will clearerr( fp ) tell fgets() that EOF has not been reached?

does fgets() gets aware when a file is updated ?

will clearerr( fp ) tell fgets() that EOF has not been reached?

If the above method is not working then you must go for closing and reopening of the file when it gets updated

Okay....I think, the following prototype might help you...
- I made this on Linux and compiled with gcc
- 'test.txt' was in the same directory as my '.c' file


int main(void)
    char buff[100];
    FILE* fp_1;

    fp_1 = fopen("./test.txt","r");

            printf("\n %s \n",buff);  //process the last appended line here
            fp_1 = fopen("./test.txt","r");


    return 0;

thx for the code.
but because there is an infinite loop cpu usage is 100%.
do you know how to prevent this ?

You could try using sleep(n) in the loop body. This will make your code defer to some other thread for at least n milliseconds, and free up the CPU. Note: is _sleep() under Win32

You may check out that are there any kind of signals that are generated and can be handled when a text file gets updated....if yes, then you can use signal handling and make your program wait until a signal is received and then process the data in file....that will definitely reduce your CPU usage...

hi everyone.

i modified [B]me_ansh[/B] code and its working.
The problem is that when it reaches the last line the program crashes
(segmentation fault)

Plz help.

My implementation:



           //process line



yes i have assigned it.

Well I guess you'll just have to post your real code, and not just random bits of pseudo-code.

hi .

i managed to find the bug. now it's not crashing.
Btw i will use use code tags next time :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.