1

我正在测试的这段代码为我提供了当前工作目录中的文件列表。

#include <stddef.h>
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>

int main (void)
{
    DIR *dp;
    struct dirent *ep;
    dp = opendir ("./");
    if (dp != NULL)
    {
        while (ep == readdir (dp))
        {
            puts (ep->d_name);
            (void) closedir (dp);
        }
    }
    else
        puts ("Couldn't open the directory.");
    return 0;
}

该代码有效,但是使用 GCC 编译给了我一个警告,告诉我(我在西班牙语中使用 GCC)可能会发生该变量ep可以在未在函数中初始化的情况下使用

我试图给变量ep一个值以避免这个警告(编程的良好实践),但是这样做会导致程序没有做它应该做的事情。

知道发生了什么,或者我做错了什么?

4

3 回答 3

4

You are equating an uninitialized variable ep to return value of a function in this line

while (ep == readdir(dp))

You want assignment

while ((ep = readdir(dp)))

If you want to read all the entries you may want to move closedir() outside the while loop

closedir(dp); //no need to cast
于 2013-10-21T12:38:27.463 回答
1

你只需要写

while ((ep = readdir(dp)))

因为写作==不会给 ep 分配任何东西。

while 条件的测试将发生在表达式的结果上ep = readdir(dp),评估为 ep 最终值。

于 2013-10-21T12:38:12.993 回答
1
  puts (ep->d_name); //you are tried access uninitialized pointer

Actually you need to read directory using readdir , readdir returns struct dirent * Now store this return value into ep and need to check readdir is success or failed.

If an error occurs, NULL is returned and errno is set appropriately.

you need to check ep is NULL or not , but you are check ep == readdir(dp)

  while (ep == readdir (dp)) ==> while (ep = readdir (dp))  
            ^^                             ^  

For clear understanding you can write

     while ( (ep == readdir (dp))  !=NULL) 
于 2013-10-21T12:45:22.673 回答