如何在扫描目录中的文件时跳过文件

Sul*_*v k -4 c

我有一个程序列出目录中的所有文件.如果文件被断开链接,我想跳过该文件并继续扫描文件中的其他文件.如果有人能指出我错在哪里,我将非常感激.以下是我的代码的一部分

d = opendir(".");
while((dir = readdir(d)) != NULL) {

 char buff[256];
 int target = readlink (dir->d_name, buff, sizeof(buff));
    if (target == -1)
    {
        printf("i found broken link  so continuing to next file..\n");
        continue;
    }
}
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是,当我只有一个断开的链接打印时

i found broken link  so continuing to next file
i found broken link  so continuing to next file
i found broken link  so continuing to next file
Run Code Online (Sandbox Code Playgroud)

并继续,直到最后一个文件.

Bas*_*tch 5

你的问题应该有一些MCVE.另请参见inode(7)符号链接(7).阅读高级Linux编程或更新的东西.

考虑使用nftw(3)fts(3)(如果需要递归扫描子目录)或者至少使用文件路径执行stat(2)(因为您正在扫描当前目录,所以不需要构造那个文件路径).记住要跳过条目...; 所以也许试试吧

 d = opendir(".");
 while((dir = readdir(d)) != NULL) {
   struct stat mystat;
   if (!strcmp(dir->d_name, ".") || !strcmp(dir->d_name, "..")) continue;
   memset (&mystat, 0, sizeof(mystat));
   if (stat(dir->d_name, &mystat) ||  S_ISLNK(mystat.st_mode))
     continue;
   /// etc...
 } 
Run Code Online (Sandbox Code Playgroud)

您可能希望处理许多情况.另见errno(3).对自己的符号链接怎么样?那么unix(7)插座怎么样?fifo(7) -s?权限?

(我们没有时间和空间来解释所有细节;你需要阅读很多)

  • 请不要只是将人们指向一堆联机帮助页,如果您已经内化了如何阅读它们,那么联机帮助页通常才有意义.另外,请推荐`fts`而不是`nftw`,因为`nftw`不保证是线程安全的,也可能不支持非常大的目录. (2认同)