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

33 lines
940 B
C
Raw Permalink Normal View History

2023-08-15 23:23:31 +08:00
/*
使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;
}