【问题标题】:C opendir always NULLC opendir 总是 NULL
【发布时间】:2017-11-11 20:52:44
【问题描述】:

所以我正在处理目录遍历,我无法让 opendir 按我想要的方式工作。它总是无法打开我发送它的目录,它给出了一些未知的错误。我通常会传入 argv[1],但我放弃了,刚开始硬编码路径。

char *dest = NULL;
char *filePath = ".";
char *newPath = NULL;


DIR *dirp;
struct dirent *dp;
int errno;
dirp = opendir("/home/cs429/Desktop/test");

struct stat path_stat;



if(dirp == NULL);
{
    // Error Handling
    fprintf(stderr, "Error failed to open input directory -%s\n",strerror(errno) );
    return 1;
}

有人知道我可以做些什么来获得 NULL 吗?我也在 gdb 中得到了这个: ../sysdeps/posix/opendir.c: 没有这样的文件或目录。

【问题讨论】:

  • 文件夹是否存在?当您在终端中键入 cd /home/cs429/Desktop/test 时会发生什么。检查路径的大小写。
  • 请启用所有警告。这是 gcc 或 clang 检测到的。

标签: c null opendir


【解决方案1】:

线

if(dirp == NULL);

什么都不做,总是执行下一个代码块,不管dirp的值是多少。

请去掉;所以代码是

if(dirp == NULL)
{
    // Error Handling
    fprintf(stderr, "Error failed to open input directory -%s\n",strerror(errno) );
    return 1;
}

【讨论】:

  • 请注意gcc -Wall(或clang)对此发出警告:foo.c:4:1: warning: this 'if' clause does not guard... [-Wmisleading-indentation] if(dirp == NULL); ^~
【解决方案2】:

首先检查给定的路径是否真的存在。

dirp = opendir("/home/cs429/Desktop/test");

手册页说“opendir()函数返回一个指向目录流的指针。出错时,返回NULL

在这里,您将dirpNULL 进行了比较,这是正确的,但您在if 语句之后放置了分号,这称为dummy if,即无论条件是否为真,立即语句将始终执行。所以去掉if之后的;

if(dirp == NULL)
{
  //some code
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-05
    • 2023-03-13
    • 1970-01-01
    • 2012-11-18
    • 2012-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多