The most efficient way is to use inotify, and the direct way is to directly use the read() system call.
using inotify
The following code may help you, it works well on Debian 7.0, GCC 4.7:
/*This is the sample program to notify us for the file creation and file deletion takes place in "/tmp/test_inotify" file*/ // Modified from: http://www.thegeekstuff.com/2010/04/inotify-c-program-example/
When starting the above program. You can verify it by creating a file or directoy named /tmp/test_inotify .
A detailed explanation can be found here.
Use read system call
If the file is open and read to the end of the current file size. the read() system call will return 0 . And if any author wrote N bytes to this file later, and then read() just returns min(N, buffersize) .
Thus, it works correctly for your circumstances. The following are sample code.
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> typedef int FD ; int main() { FD filed = open("/tmp/test_inotify", O_RDWR ); char buf[128]; if( !filed ) { printf("Openfile error\n"); exit(-1); } int nbytes; while(1) { nbytes = read(filed, buf, 16); printf("read %d bytes from file.\n", nbytes); if(nbytes > 0) { split_buffer_by_newline(buf); // split buffer by new line. } sleep(1); } return 0; }
Link
source share