我有一个程序列出目录中的所有文件.如果文件被断开链接,我想跳过该文件并继续扫描文件中的其他文件.如果有人能指出我错在哪里,我将非常感激.以下是我的代码的一部分
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)
并继续,直到最后一个文件.
你的问题应该有一些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?权限?
(我们没有时间和空间来解释所有细节;你需要阅读很多)
| 归档时间: |
|
| 查看次数: |
268 次 |
| 最近记录: |