gpt4 book ai didi

c - 使用 readdir() 读取目录时删除文件

转载 作者:太空狗 更新时间:2023-10-29 15:00:00 44 4
gpt4 key购买 nike

我的代码是这样的:

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 readdir :

If a file is removed from or added to the directory after the most recent call to opendir() or rewinddir(), whether a subsequent call to readdir() returns an entry for that file is unspecified.

所以,我的猜测是......这取决于。

这取决于操作系统、一天中的时间、添加/删除文件的相对顺序、...

此外,在 readdir() 函数返回和您尝试 unlink() 文件之间,某些其他进程可能已经删除了该文件文件和你的 unlink() 失败。


编辑

我用这个程序测试过:

#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()readdir() 之间创建的文件。但是在另一台计算机上可能会有所不同;如果我用不同的选项编译,它在我的电脑上可能会有所不同;如果我升级内核可能会有所不同; ...

关于c - 使用 readdir() 读取目录时删除文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1676522/

44 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com