我想在目录中监视来自C应用程序的新文件。但是,我对修改后的文件不感兴趣,仅对新文件感兴趣。目前,我为此目的使用readdir / stat:
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\n", 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\n", s_date, ent->d_name ); *timestamp = statbuf.st_mtime; } } }
知道如何在不保留文件列表的情况下检测 Linux和Solaris 10 上新创建的文件吗?
解决方案是将最后访问时间存储在全局变量中,并使用过滤器选择最新文件scandir():
scandir()
int cmp_mtime( const struct dirent** lentry, const struct dirent** rentry ):
int cmp_mtime( const struct dirent** lentry, const struct dirent** rentry )
(*lentry)->d_name
ltime = statbuf.st_mtime;
(*rentry)->d_name
rtime = statbuf.st_mtime;
if ( ltime < rtime ) return -1;
else if ( ltime > rtime ) return 1;
return 0;
int selector( const struct dirent* entry ):
int selector( const struct dirent* entry )
entry->d_name
stat.st_mtime > lastseen
主要:
lastseen
scandir( directory, &entries, selector, cmp_mtime );