常用函数如下:
opendir():打开指定的目录,并返回DIR*形态的目录流,
#include <sys/types.h>
#include <dirent.h>
DIR *opendir(const char *name);
参数含义:
name:路径名字。
返回值:成功返回打开的目录流,失败返回 NULL。
closedir():关闭目录流。
#include <sys/types.h>
#include <dirent.h>
int closedir(DIR *dirp);
参数含义:dirp:要关闭的目录流指针。
实验代码在dir.c:路径为:11_Linux系统开发进阶\Linux系统编程_章节使用资料。
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include <stdio.h>
int main(int argc, const char *argv[])
{
DIR * dir;
struct dirent * pd;
dir = opendir("./");
while((pd = readdir(dir)) != NULL){
printf(" %s \t ",pd->d_name);
}
printf("\n");
closedir(dir);
return 0;
}
编译执行,即可看到目录下的文件:



本文介绍了如何在C语言中使用opendir()函数打开并遍历指定目录,以及closedir()函数用于关闭目录流。通过实例展示了如何获取目录下文件名并进行操作。
356

被折叠的 条评论
为什么被折叠?



