gpt4 book ai didi

c - readdir() 如何与 rename() 结合使用?

转载 作者:太空宇宙 更新时间:2023-11-04 02:42:57 25 4
gpt4 key购买 nike

我编写了一个函数来重命名目录中的文件,以便它们按数字顺序命名。不幸的是,这个函数似乎丢弃了一些文件并重命名了一些。可能,我不明白 readdir() 和 rename() 背后的逻辑。谁能帮忙,这是我的代码摘录;

while(((entry->readdir(dirp))!=NULL)
{
strcpy(t1_string,entry->d_name);
exception1=strcmp(entry->d_name,".");
exception2=strcmp(entry->d_name,"..");
exception3=strcmp(entry->d_name,".svn");
if((exception1!=0)&&(exception2!=0)&&(exception3!=0))
{
token2=strchr(t1_string,'.'); //extension part
num_files++;
if(num_files%4==1)
utt++;
sprintf(utt_n,"%d",utt);
strcpy(newfilename, utt_s); //utt_s is a constant string
strcat(newfilename,utt_n);
strcat(newfilename,token2);
rename(entry->d_name,newfilename);
}
} //End of the while loop

最佳答案

这很可能是由于竞争条件造成的;您实际上是在迭代数据结构的同时修改它。当然,数据结构是文件系统对目录中文件名称的想法。

正如评论中所指出的,在 Open Group 的 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.

更好的方法是分两个阶段进行:

  1. 收集所有的名字。
  2. 进行所需的重命名。

当然,您必须做好重命名失败的准备,因为其他进程可以与您并行重命名或删除文件。

关于c - readdir() 如何与 rename() 结合使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30028756/

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