Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
776 views
in Technique[技术] by (71.8m points)

c - Monitor directory for new files only

I'd like to monitor a directory for new files from a C app. However, I'm not interested in modified files, only in new files. Currently I'm using readdir/stat for that purpose:

while ( (ent = readdir(dir)) != NULL ) {
  strcpy(path, mon_dir);
  strcat(path, "/");
  strcat(path, ent->d_name);
  if ( stat(path, &statbuf) == -1 ) {
    printf( "Can't stat %s
", ent->d_name );
    continue;
  }
  if ( S_ISREG(statbuf.st_mode) ) {
    if ( statbuf.st_mtime > *timestamp ) {
      tcomp = localtime( &statbuf.st_mtime );
      strftime( s_date, sizeof(s_date), "%Y%m%d %H:%M:%S", tcomp );
      printf( "%s %s was added
", s_date, ent->d_name );
      *timestamp = statbuf.st_mtime;
    }
  }
}

Any idea how I can detect newly created files on Linux AND Solaris 10 without keeping a list of files?

Cheers,

Martin.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

gamin provides an abstraction around system dependant file notification apis for many *nixes , and it's included in many linux distros by default.

For linux, you could use the linux specific inotify api.

Win32 has a similar API via FindFirstChangeNotification


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...