C++ 如何检查目录是文件还是文件夹?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3844546/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 13:52:50 来源:igfitidea点击:
How do I check if a directory is a file or folder?
提问by William
Okay, so I'm using mingW, and the direct struct has no variables named d_type or stat, d_stat, or dd_stat. I need to know how I can use my direct struct to figure out if what I have is a file or folder. Here is my code.
好的,所以我使用 mingW,并且直接结构没有名为 d_type 或 stat、d_stat 或 dd_stat 的变量。我需要知道如何使用我的直接结构来确定我拥有的是文件还是文件夹。这是我的代码。
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <errno.h>
#include <vector>
#include <string>
#include <iostream>
using namespace std;
/*function... might want it in some class?*/
int getdir (string dir, vector<string> &files)
{
DIR *dp;
struct stat _buf;
struct dirent *dirp;
if((dp = opendir(dir.c_str())) == NULL) {
cout << "Error(" << errno << ") opening " << dir << endl;
return errno;
}
while ((dirp = readdir(dp)) != NULL) {
if(stat(dirp->d_name, &_buf) != 0x4)
files.push_back(string(dirp->d_name));
}
closedir(dp);
return 0;
}
int main()
{
string dir = string(".");
vector<string> files = vector<string>();
getdir(dir,files);
for (unsigned int i = 0;i < files.size();i++) {
cout << files[i] << endl;
}
return 0;
}
回答by mr. Vachovsky
boost::filesystem::is_directory()
//I found it )
//So, also you can try to call stat() function. ( on Windows )
(^_^)
(^_^)