你提到的 “ubuntu copendir” 应该是 opendir 在 Ubuntu 下的使用(C 语言里用来打开目录的函数),很可能你是想问:新手在 Ubuntu 上怎么学习用 opendir 来读目录。
下面我用新手视角 + 一步一步来讲。
opendir 是什么?opendir 是 C 语言里的一个函数,用来打开一个目录,配合:
readdir:读目录里的文件closedir:关闭目录头文件:
#include <dirent.h>
函数原型:
DIR *opendir(const char *name);
sudo apt update
sudo apt install gcc
检查:
gcc --version
opendir 示例(强烈建议先抄)#include <stdio.h>
#include <dirent.h>
int main() {
DIR *dir;
struct dirent *entry;
dir = opendir("."); // 打开当前目录
if (dir == NULL) {
perror("opendir");
return 1;
}
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
保存为 listdir.c
gcc listdir.c -o listdir
./listdir
你会看到:
.
..
file1.txt
test.c
#include <dirent.h>会报错:opendir 未声明
if (dir == NULL)
目录不存在时会崩
closedir会内存/资源泄漏
#include <sys/stat.h>
struct stat st;
stat(entry->d_name, &st);
if (S_ISREG(st.st_mode)) {
printf("文件: %s\n", entry->d_name);
}
printf, 指针)gcc 编译opendir + readdirstat 判断文件类型如果你愿意,可以告诉我:
我可以直接按你的水平来教。