用C++写一个遍历文件的操作
时间: 2023-12-27 07:49:46 浏览: 23
以下是用C语言遍历文件的示例代码:
```
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
void scan_dir(char *dir) {
DIR *dp;
struct dirent *entry;
struct stat statbuf;
if ((dp = opendir(dir)) == NULL) {
fprintf(stderr, "Cannot open directory: %s\n", dir);
return;
}
chdir(dir);
while ((entry = readdir(dp)) != NULL) {
lstat(entry->d_name, &statbuf);
if (S_ISDIR(statbuf.st_mode)) {
if (strcmp(".", entry->d_name) == 0 || strcmp("..", entry->d_name) == 0) {
continue;
}
printf("%s/\n", entry->d_name);
scan_dir(entry->d_name);
} else {
printf("%s\n", entry->d_name);
}
}
chdir("..");
closedir(dp);
}
int main(int argc, char **argv) {
if (argc != 2) {
printf("Usage: %s <directory>\n", argv[0]);
return 0;
}
scan_dir(argv[1]);
return 0;
}
```
这个程序接受一个参数,即目录名,然后遍历该目录和其子目录,并打印出所有文件和目录的名称。它使用了 opendir()、readdir() 和 closedir() 函数来打开、读取和关闭目录,使用了 lstat() 函数来获取文件的信息,使用了 chdir() 函数来进入和退出子目录。程序也处理了 "." 和 ".." 目录,以避免无限循环。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)