c++和linux指定一个路径,遍历路径下所有文件和目录,并输出文件和目录的名称
时间: 2024-03-02 09:48:30 浏览: 21
您可以使用C++和Linux系统的文件操作函数来实现此功能。以下是一个简单的例子:
```cpp
#include <iostream>
#include <dirent.h>
#include <cstring>
using namespace std;
int main() {
string path = "/your/path/to/directory"; // 指定要遍历的目录路径
DIR *dir;
struct dirent *ent;
if ((dir = opendir(path.c_str())) != NULL) {
while ((ent = readdir(dir)) != NULL) {
if (strcmp(ent->d_name, ".") != 0 && strcmp(ent->d_name, "..") != 0) {
// 排除当前目录和父目录
if (ent->d_type == DT_DIR) {
// 如果是目录
cout << "dir: " << ent->d_name << endl;
} else {
// 如果是文件
cout << "file: " << ent->d_name << endl;
}
}
}
closedir(dir);
} else {
cout << "Error opening directory." << endl;
}
return 0;
}
```
该程序首先指定要遍历的目录路径,然后使用`opendir`函数打开该目录。接着使用`readdir`函数遍历目录下的所有文件和目录,使用`strcmp`函数判断是否为当前目录和父目录,然后根据`d_type`值判断文件类型并输出名称。最后使用`closedir`函数关闭目录。