我有这个代码打开一个目录,并检查列表是不是一个常规文件(意味着它是一个文件夹),它也将打开它.如何用C++区分文件和文件夹.如果这有帮助,这是我的代码:
#include <sys/stat.h>
#include <cstdlib>
#include <iostream>
#include <dirent.h>
using namespace std;
int main(int argc, char** argv) {
// Pointer to a directory
DIR *pdir = NULL;
pdir = opendir(".");
struct dirent *pent = NULL;
if(pdir == NULL){
cout<<" pdir wasn't initialized properly!";
exit(8);
}
while (pent = readdir(pdir)){ // While there is still something to read
if(pent == NULL){
cout<<" pdir wasn't initialized properly!";
exit(8);
}
cout<< pent->d_name << endl;
}
return 0;
Run Code Online (Sandbox Code Playgroud)
}
一种方法是:
switch (pent->d_type) {
case DT_REG:
// Regular file
break;
case DT_DIR:
// Directory
break;
default:
// Unhandled by this example
}
Run Code Online (Sandbox Code Playgroud)
您可以struct dirent在GNU C Library Manual上查看文档.
| 归档时间: |
|
| 查看次数: |
2651 次 |
| 最近记录: |