我开始学习 C,我需要一些帮助来理解这段代码:
#include "apue.h"
#include <dirent.h>
int main(int argc, char *argv[])
{
DIR *dp;
struct dirent *dirp;
if (argc != 2)
err_quit("usage: ls directory_name");
if ((dp = opendir(argv[1])) == NULL)
err_sys("can't open %s", argv[1]);
while ((dirp = readdir(dp)) != NULL)
printf("%s\n", dirp->d_name);
closedir(dp);
exit(0);
}
所以,我知道第一个 if 会告诉你你缺少要列出文件的目录,但我完全迷失了下一个 if 和 while,我知道这将打印文件,但我无法理解当时的情况,任何帮助将不胜感激,谢谢!
最佳答案
- If条件将打开要从中读取文件的主目录。如果打开失败,则返回NULL。
- 其次,while条件将从给定目录中一一读取文件并打印文件名。
readdir
将从目录中读取第一个文件,如果读取文件失败将返回NULL。- 所以在 while 条件下,如果
readdir
成功读取文件,那么它不会返回 NULL。所以现在条件变成while(dirp != NULL)
。
关于c - 列出 C 目录上的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35145657/