Emi*_*lio 5 c c++ filesystems dirent.h
如果文件是常规文件(并且不是目录,管道等),我如何签入C++?我需要一个函数isFile().
DIR *dp;
struct dirent *dirp;
while ((dirp = readdir(dp)) != NULL) {
if ( isFile(dirp)) {
cout << "IS A FILE!" << endl;
i++;
}
Run Code Online (Sandbox Code Playgroud)
我已经尝试将dirp-> d_type与(unsigned char)0x8进行比较,但它似乎无法通过不同的系统进行移植.
Joh*_*itb 23
您可以使用可移植的boost::filesystem
(标准C++库在最近在C++ 17中引入std :: filesystem之前无法做到这一点):
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
#include <iostream>
int main() {
using namespace boost::filesystem;
path p("/bin/bash");
if(is_regular_file(p)) {
std::cout << "exists and is regular file" << std::endl;
}
}
Run Code Online (Sandbox Code Playgroud)
您需要对文件调用 stat(2),然后在 st_mode 上使用 S_ISREG 宏。
类似的东西(改编自这个答案):
#include <sys/stat.h>
struct stat sb;
if (stat(pathname, &sb) == 0 && S_ISREG(sb.st_mode))
{
// file exists and it's a regular file
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
12474 次 |
最近记录: |