在 Ubuntu(Linux)上测试 opendir(),通常是指用 C/C++ 写一个程序调用 opendir() 打开目录,并验证它是否成功。下面给你一个从零开始的完整示例,包括编译、运行和常见测试方法。
opendir() 是 POSIX 标准函数,用于打开一个目录流,定义在:
#include <dirent.h>
#include <sys/types.h>
函数原型:
DIR *opendir(const char *name);
DIR*NULL,并设置 errno确保已安装 gcc:
sudo apt update
sudo apt install gcc
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <errno.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("opendir 成功: %s\n", argv[1]);
closedir(dir);
return 0;
}
gcc test_opendir.c -o test_opendir
./test_opendir /home
输出:
opendir 成功: /home
./test_opendir /not_exist
输出:
opendir 失败: No such file or directory
./test_opendir /root
输出:
opendir 失败: Permission denied
如果你想验证 opendir + readdir 是否真的能读目录:
#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) {
perror("opendir");
return 1;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
确保包含:
#include <dirent.h>
openDirclosedir()echo $?
✅ Ubuntu 测试 opendir 的核心步骤:
opendir() 打开目录如果你是想:
可以继续问我,我可以给你更具体的测试方案。