我的代码是这样的:
DIR* pDir = opendir("/path/to/my/dir");
struct dirent pFile = NULL;
while ((pFile = readdir())) {
// Check if it is a .zip file
if (subrstr(pFile->d_name,".zip") {
// It is a .zip file, delete it, and the matching log file
char zipname[200];
snprintf(zipname, sizeof(zipname), "/path/to/my/dir/%s", pFile->d_name);
unlink(zipname);
char* logname = subsstr(zipname, 0, strlen(pFile->d_name)-4); // Strip of .zip
logname = appendstring(&logname, ".log"); // Append .log
unlink(logname);
}
closedir(pDir);
(此代码未经测试,纯粹是一个示例)
重点是:在使用 readdir() 循环遍历目录时是否允许删除目录中的文件?
或者 readdir() 仍然会找到已删除的 .log 文件吗?
引用自POSIX 读目录 https://pubs.opengroup.org/onlinepubs/9699919799/functions/readdir.html:
如果文件被删除或添加到
最近的目录之后
调用 opendir() 或 rewinddir(),
是否随后调用 readdir()
返回该文件的条目是
未指定。
所以,我的猜测是……这要看情况。
这取决于操作系统、一天中的时间、添加/删除文件的相对顺序,...
而且,作为进一步的一点,在这段时间之间readdir()
函数返回并且你尝试unlink()
该文件,其他一些进程可能已删除该文件和您的unlink()
fails.
Edit
我用这个程序测试过:
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
int main(void) {
struct dirent *de;
DIR *dd;
/* create files `one.zip` and `one.log` before entering the readdir() loop */
printf("creating `one.log` and `one.zip`\n");
system("touch one.log"); /* assume it worked */
system("touch one.zip"); /* assume it worked */
dd = opendir("."); /* assume it worked */
while ((de = readdir(dd)) != NULL) {
printf("found %s\n", de->d_name);
if (strstr(de->d_name, ".zip")) {
char logname[1200];
size_t i;
if (*de->d_name == 'o') {
/* create `two.zip` and `two.log` when the program finds `one.zip` */
printf("creating `two.zip` and `two.log`\n");
system("touch two.zip"); /* assume it worked */
system("touch two.log"); /* assume it worked */
}
printf("unlinking %s\n", de->d_name);
if (unlink(de->d_name)) perror("unlink");
strcpy(logname, de->d_name);
i = strlen(logname);
logname[i-3] = 'l';
logname[i-2] = 'o';
logname[i-1] = 'g';
printf("unlinking %s\n", logname);
if (unlink(logname)) perror("unlink");
}
}
closedir(dd); /* assume it worked */
return 0;
}
在我的电脑上,readdir()
查找已删除的文件,但不查找之间创建的文件opendir()
and readdir()
。但在另一台电脑上可能会有所不同;如果我使用不同的选项进行编译,在我的计算机上可能会有所不同;如果我升级内核可能会有所不同; ...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)