在 Ubuntu / Linux 下,opendir 是 C 语言库函数(在 <dirent.h> 中),不是命令行命令。
它的“参数”是目录路径,下面详细说明。
#include <dirent.h>
DIR *opendir(const char *name);
name:目录的路径(字符串)
"/home/user""." 或 "testdir"DIR *(目录流指针)NULL,并设置 errnoDIR *dir = opendir(".");
DIR *dir = opendir("/home/ubuntu/logs");
char *path = argv[1];
DIR *dir = opendir(path);
#include <stdio.h>
#include <dirent.h>
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("用法: %s <目录>\n", argv[0]);
return 1;
}
DIR *dir = opendir(argv[1]);
if (dir == NULL) {
perror("opendir 失败");
return 1;
}
printf("成功打开目录: %s\n", argv[1]);
// 这里可以用 readdir(dir) 读取文件
closedir(dir);
return 0;
}
编译运行:
gcc test.c -o test
./test /tmp
| 情况 | 原因 |
|---|---|
opendir 返回 NULL |
路径不存在 / 无权限 |
| 路径是文件不是目录 | 不能 opendir |
忘了 closedir |
内存/资源泄漏 |
如果你其实是想问 Shell 命令(不是 C 函数),可能是:
ls 目录cd 目录find 目录可以告诉我你具体是在 写 C 程序 还是 用终端命令,我可以更精准回答。