qfedu-linux-advanced-level/day2/homework/h5.c

33 lines
940 B
C
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
编写一个程序使用opendir系统调用打开一个已存在的目录并使用readdir系统调用遍历目录中的文件和子目录并将它们的名称打印到控制台上。
*/
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <string.h>
int main(int argc, char const *argv[])
{
DIR *dir = opendir("/home/flykhan/qfedu-linux-advanced-level");
if (NULL == dir)
{
perror("opendir"); // 打开目录失败时输出错误信息
return -1;
}
struct dirent *dirent;
while ((dirent = readdir(dir)) != NULL)
{
if (strcmp(dirent->d_name, ".") != 0 && strcmp(dirent->d_name, "..") != 0)
{
if (dirent->d_type == DT_DIR || dirent->d_type == DT_REG)
{
printf("%s\n", dirent->d_name); // 打印目录中的文件和子目录名
}
}
}
closedir(dir); // 关闭目录
return 0;
}