【问题标题】:lstat returning <0lstat 返回 <0
【发布时间】:2016-10-28 00:44:25
【问题描述】:

基本上,这应该是一段简单的代码,用于打开目录流并查找符号链接。每当找到符号链接时,它应该打印 ("Symbolic link found"); 但是,lstat(dirp-&gt;d_name,&amp;bufcall 总是返回值 ln -s ciao.txt link1 和 ln -s ciao2.txt link2 我知道我应该稍后在我的代码中调用closedir(),请不要关心这个。

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>

void main (int argc, char* argv[])
{
    char buffer[100],dir[100];
    struct stat buf;
    int x;
    DIR *dp;
    struct dirent *dirp;
    if((dp=opendir(argv[1]))==NULL)
    {
        printf("\nError opening directory stream, now exiting...\n");
        exit(-1);
    }
    while((dirp=readdir(dp))!=NULL)
        {
            lstat(dirp->d_name,&buf);
            if(S_ISLNK(buf.st_mode))    
                printf("\n%s Is a symbolic link\n",dirp->d_name);
            else
                printf("\n%s Is not a symbolic link\n",dirp->d_name);



        }


}

我们将不胜感激。谢谢。

【问题讨论】:

  • 我检查了 lstat 调用,它返回

标签: c file stream macros directory


【解决方案1】:

d_name 是目录中的文件名,不是完整路径名。您必须将chdir 放入您正在查看的目录中,或者为文件构建完整路径名。

最简单的解决方案是在 while 循环之前添加这一行:

chdir(argv[1]);

【讨论】:

  • 感谢您的快速答复。基本上,如果我想以“我的方式”这样做,我需要一个完整的路径名,例如 /home/myuser/Desktop/myfile 等,对吧?
  • 是的,如果你不想使用chdir你需要构造文件的完整路径名。 (或者,为了完整起见,您还可以使用相对路径名,例如 ../../../Desktop/myfile。)
  • 最后一件事,因为您似乎对 C 中的文件非常有信心。您知道如何避免在我的代码中出现 ... 文件吗?我什至不知道他们指的是什么。谢谢。
  • . 是指向当前目录的链接,.. 是指向目录树中父目录的链接。只需检查这些文件名,例如使用strcmp,然后跳过它们。
猜你喜欢
  • 1970-01-01
  • 2015-06-15
  • 1970-01-01
  • 2015-06-21
  • 2019-02-20
  • 2015-06-17
  • 2012-01-04
  • 2018-02-23
  • 2012-03-31
相关资源
最近更新 更多