Linux Opendir and Readdir won't update along with directory changingtable of Contents
- 1. Result
- 2. Temporary Fix method
- 3. Test
1Result
According to my experiment, opendir () would just record a static state of opened directory. During the readdir () operation, if you add/remove a file to the directory opened by Opendir (), readd IR () knows nothing about it.
2Temporary fix method
Use the access () to judge if some file existed.
3Test
~ddd$ Touch a.tmp b.tmp c.tmp a.aa B.aa
./readdir-test DDD
A.aa a.tmp b.aa b.tmp c.tmp*******************************[0], Full name was ddd/a.aa[1], full name is ddd/. [2], full name is Ddd/c.tmp=====================================all. AA deleted.a.tmp b.tmp c.tmp=========== ==========================[3], full name was DDD/B.AA//shouldn ' t show B.aa nowddd/b.aa not exist. [4], full name is ddd/b.tmprm:cannot remove ' ddd/*.aa ': No such file or Directory=====================================all . AA deleted.a.tmp b.tmp c.tmp=====================================[5], full name is ddd/.[ 6], full name is ddd/a.tmprm:cannot remove ' ddd/*.aa ': No such file or Directory=====================================all . AA deleted.a.tmp b.tmp c.tmp=====================================
#include <stdio.h>#include <sys/types.h>#include <string.h>#include <unistd.h>#include <stdlib.h>#include <dirent.h>int Main(int argc,Char*argv[]){DIR*Pdir=NULL;struct dirent*pdirent=NULL;Char fname[256];Char cmd[256];Static int I= 0;if(argc! = 2) {printf ("Usage:%s dir\n", Argv[0]);return-1; } Pdir = Opendir (argv[1]);if(Pdir = =NULL)return-1; printf"*******************************\n"); sprintf (CMD,"ls%s", argv[1]); System (CMD); printf"*******************************\n"); while((pdirent = Readdir (pdir))! =NULL) {sprintf (fname,"%s/%s", argv[1], pdirent->d_name); printf"[%d], full name is%s\n", i++, fname);if(Access (fname, F_OK)! = 0) {printf ('%s not exist.\n ', fname);Continue; }if(STRNCMP (Fname+strlen (fname)-4,". tmp", 4) = = 0) {sprintf (cmd,"rm%s/*.aa", argv[1]); System (CMD); printf"=====================================\n"); printf"all. AA deleted.\n"); sprintf (CMD,"ls%s", argv[1]); System (CMD); printf"=====================================\n"); }} closedir (Pdir);return0;}
Output result is
Linux Opendir and Readdir won't update along with directory changing