你提到的 “ubuntu copendir” 很可能是 opendir(不是 copendir,在 Linux 里没有 copendir 这个标准函数)。
opendir 是 C 语言里用来打开目录、读取目录内容 的函数,新手在 Ubuntu 上常会用到。
下面从 是什么 → 怎么写 → 怎么编译运行 一步一步讲。
opendir 是 POSIX 标准函数,用来打开一个目录,配合:
readdir:读取目录中的文件closedir:关闭目录头文件:
#include <dirent.h>
函数原型:
DIR *opendir(const char *name);
返回值:
DIR *NULL#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;
}
sudo apt update
sudo apt install build-essential
nano listdir.c
把上面的代码粘进去,保存退出。
gcc listdir.c -o listdir
./listdir
你会看到当前目录下的所有文件和文件夹名。
opendir("/home/yourname");
. 和 ..if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
#include <sys/stat.h>
struct stat st;
stat(entry->d_name, &st);
if (S_ISDIR(st.st_mode))
printf("[目录] %s\n");
你可能是想问:
opendir 用法(上面已讲)ls, cd)os.listdirstd::filesystem可以告诉我你是 写 C 程序 / 用命令 / 学 Python,我可以按你的情况讲。