在Linux环境编程中,有时我们需要对目录进行操作,判断该目录下的文件大小和检索目录等功能,本篇记录opendir, readdir, closedir的使用。
使用man 3 opendir命令查看帮助文档
1.opendir函数打开并返回指向目录流的指针。这个流位于目录中的第一个条目处。
函数名 | opendir |
相关函数 | readdir |
表头文件 | #include <dirent.h> |
函数定义 | DIR *opendir(const char *name); |
函数说明 | 打开并返回指向目录流的指针。这个流位于目录中的第一个条目处。 |
返回值 | 成功返回指向的目录流指值,失败返回nullptr |
示例:
#include <iostream>
#include <sys/types.h>
#include <dirent.h>
using namespace std;
int main()
{
DIR* pDir= opendir("/home/scott/projects");
if (pDir == NULL)
{
perror("opendir failed.\n");
}
else
{
printf("pDir==============================%p\n", pDir);
}
DIR* pDir1 = opendir("/home/scott/projects1");
if (pDir1 == NULL)
{
perror("/home/scott/projects1==================opendir failed.\n");
}
else
{
printf("pDir1==============================%p\n", pDir1);
}
cout << "hello Ubuntu 1804" << endl;
return 0;
}
运行结果:
2.readdir()函数返回一个指向dirt结构的指针,该结构表示dirp指向的目录流中的下一个目录条目。当到达目录流的末尾或发生错误时,它将返回NULL。
函数名 | readdir |
相关函数 | opendir |
表头文件 | #include <dirent.h> |
函数定义 | struct dirent *readdir(DIR *dirp); |
函数说明 | 返回一个指向dirt结构的指针,该结构表示dirp指向的目录流中的下一个目录条目。 struct dirent { |
返回值 | 成功返回指向dirt结构的指针,失败返回nullptr |
示例:
#include <iostream>
#include <sys/types.h>
#include <dirent.h>
using namespace std;
int main()
{
DIR* pDir = opendir("/home/scott/projects");
if (pDir == NULL)
{
perror("opendir failed.\n");
}
struct dirent* pDirent;
std::string picture("getIP.c");
std::string str;
while ((pDirent = readdir(pDir)) != nullptr)
{
printf("d_name: %s\n", pDirent->d_name);
printf("d_ino: %d\n", pDirent->d_ino);
printf("d_off: %d\n", pDirent->d_off);
printf("d_reclen: %d\n", pDirent->d_reclen);
printf("d_type: %d\n", pDirent->d_type);
printf("\n");
str = pDirent->d_name;
if (str.find(picture) != str.npos)
{
std::cout << "find================string name: " << str << std::endl;
break;
}
}
cout << "hello Ubuntu 1804" << endl;
return 0;
}
运行结果:
3.closedir函数关闭打开的目录流。
函数名 | closedir |
相关函数 | readdir,opendir |
表头文件 | #include <dirent.h> |
函数定义 | int closedir(DIR *dirp); |
函数说明 | 关闭打开的目录流。 |
返回值 | 成功返回0,失败返回非0 |
使用opendir打开目录流,使用后没有关闭会引用内存泄露,下面通valgrind工具来检测这个功能。
首先写一个opendir目录流的小程序。
示例:
#include <iostream>
#include <sys/types.h>
#include <dirent.h>
using namespace std;
int main()
{
DIR* pDir = opendir("/home/scott/projects");
if (pDir == NULL)
{
perror("opendir failed.\n");
}
int ret = closedir(pDir);
printf("pDir==============================%p\n", pDir);
cout << "hello Ubuntu 1804" << endl;
return 0;
}
编译生成可执行程序linuxAPI.out
然后用valgrind检测。
valgrind --leak-check=full ./linuxAPI.out
下面把
int ret = closedir(pDir);
这行代码注释掉,重新编译生成可以执行程序,再次检测。
从上面检测结果看出内存泄露了32816个字节。
参考:
Linux C编程 打开目录后,不使用closedir()函数,会有什么样的影响?_opendir需要closedir吗-优快云博客