
C语言中,opendir() 函数打开目录后,使用 readdir() 函数读取目录项。readdir() 返回 NULL 即表示已到达目录末尾。
以下示例演示如何检测 opendir() 是否遍历完成:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
int main() {
DIR *dir;
struct dirent *entry;
// 打开当前目录
dir = opendir(".");
if (dir == NULL) {
perror("opendir");
return EXIT_FAILURE;
}
// 循环读取目录项,直到到达末尾
while ((entry = readdir(dir)) != NULL) {
printf("目录项: %s\n", entry->d_name);
}
// 关闭目录
closedir(dir);
printf("目录遍历完成\n"); // 添加提示信息,明确遍历结束
return EXIT_SUCCESS;
}代码首先使用 opendir() 打开当前目录 (.)。然后,while 循环不断调用 readdir() 读取目录项,直到 readdir() 返回 NULL,表示遍历结束。最后,closedir() 关闭目录,并打印提示信息确认遍历完成。 错误处理也包含在内,确保程序在 opendir() 失败时能正确处理。
以上就是如何判断copendir是否到达末尾的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号