[英]Distinguish between folders and files in C++
我有這個代碼打開一個目錄,並檢查列表是不是一個常規文件(意味着它是一個文件夾),它也將打開它。 如何用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;
}
一種方法是:
switch (pent->d_type) {
case DT_REG:
// Regular file
break;
case DT_DIR:
// Directory
break;
default:
// Unhandled by this example
}
您可以在GNU C Library Manual上看到struct dirent
文檔。
為了完整起見,另一種方式是:
struct stat pent_stat;
if (stat(pent->d_name, &pent_stat)) {
perror(argv[0]);
exit(8);
}
const char *type = "special";
if (pent_stat.st_mode & _S_IFREG)
type = "regular";
if (pent_stat.st_mode & _S_IFDIR)
type = "a directory";
cout << pent->d_name << " is " << type << endl;
如果文件名不同,則必須使用原始目錄修補文件名.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.