大同市网站建设_网站建设公司_代码压缩_seo优化
2026/1/7 16:14:28 网站建设 项目流程

用于关闭目录流的函数。

1.头文件

#include <sys/types.h>

#include <dirent.h>

2.函数原型

int closedir(DIR *dirp);

3.参数

dirp: 指向 DIR 结构的指针,该结构由 opendir() 返回。它表示要关闭的目录流。

4.返回值

成功: 返回 0。失败: 返回 -1,并设置 errno 以指示错误类型。

5.示例:(打开目录,并查看目录中的文件)

#include <stdio.h>

#include <stdlib.h>

#include <sys/stat.h>

#include <dirent.h>

#include <errno.h>

#include <unistd.h>

int main(){

const char *dir_path = "directory";

struct stat statbuf;

DIR *dir;

struct dirent *entry;

int file_count=0;

printf("File name:%s\n", dir_path);

if (stat(dir_path, &statbuf) == -1) {

perror("stat");

return 1;

}

if (S_ISDIR(statbuf.st_mode)) {

printf("It's the directory: YES\n");

} else {

printf("It's the directory: NO\n");

}

dir = opendir(dir_path);

if (dir == NULL) {

perror("opendir");

return 1;

}

printf("Directory Contents:\n");

while ((entry = readdir(dir)) != NULL) {

printf("\t%s\t%ld\n",entry->d_name,entry->d_ino);

file_count ++;

if (file_count == 3) {

printf("Resetting directory stream...\n");

rewinddir(dir);

}

}

if (errno != 0) {

perror("readdir");

closedir(dir);

return EXIT_FAILURE;

}

closedir(dir);

return 0;

}

接下来需要自行创建directory文件夹,下图是directory文件夹结构:

$ tree directory/

directory/

├── 1

├── 2

├── 3

├── 4.txt

├── 5.txt

└── 6.txt

3 directories, 3 files

6.查看执行结果

File name:directory

It's the directory: YES

Directory Contents:

1 5255834

3 5255836

6.txt 5255839

Resetting directory stream...

1 5255834

3 5255836

6.txt 5255839

.. 5255821

5.txt 5255838

2 5255835

4.txt 5255837

. 5255833

可以看到,首先打印出来要检查的directory文件名,之后检查directory文件为文件夹,在之后开始打印文件夹中的内容,当DIR 结构体的指针指向第三个文件后,使用rewinddir()函数重置目录流,直到打印完毕directory文件夹中的内容。同时我们也看到文件并不是按规律打印出来的,也印证了前面介绍的文件存储顺序取决于文件系统向该目录添加文件时所遵循的顺序,和在文件被删除以后对目录列表中空隙的填补方式,并不是使用ls命令查看到的有序排列的顺序。

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询