C++ 区分C+中的文件夹和文件+;
我有一段代码,可以打开一个目录并检查列表是否是一个普通文件(意味着它是一个文件夹),它也会打开它。如何区分文件和文件夹与C++。 如果这有帮助,下面是我的代码:C++ 区分C+中的文件夹和文件+;,c++,C++,我有一段代码,可以打开一个目录并检查列表是否是一个普通文件(意味着它是一个文件夹),它也会打开它。如何区分文件和文件夹与C++。 如果这有帮助,下面是我的代码: #include <sys/stat.h> #include <cstdlib> #include <iostream> #include <dirent.h> using namespace std; int main(int argc, char** argv) { // Poin
#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;
#包括
#包括
#包括
#包括
使用名称空间std;
int main(int argc,字符**argv){
//指向目录的指针
DIR*pdir=NULL;
pdir=opendir(“.”);
struct dirent*pent=NULL;
如果(pdir==NULL){
cout一种方法是:
switch (pent->d_type) {
case DT_REG:
// Regular file
break;
case DT_DIR:
// Directory
break;
default:
// Unhandled by this example
}
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;
您可以在上查看struct dirent
文档。要了解完整性,另一种方法是:
switch (pent->d_type) {
case DT_REG:
// Regular file
break;
case DT_DIR:
// Directory
break;
default:
// Unhandled by this example
}
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;
struct stat pent_stat;
if(状态(pent->d_name和pent_状态)){
perror(argv[0]);
出口(8);
}
const char*type=“特殊”;
if(pent_stat.st_模式和S_IFREG)
type=“常规”;
if(pent_stat.st_mode&_S_IFDIR)
type=“a目录”;
不能使用stat
(或lstat
)和S\u ISDIR
。