如何检查文件是否为常规文件? [英] How do i check if a file is a regular file?
本文介绍了如何检查文件是否为常规文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何在C ++中检查文件是否为常规文件(而不是目录,管道等)?我需要一个函数isFile().
How do i check in C++ if a file is a regular file (and is not a directory, a pipe, etc.)? I need a function isFile().
DIR *dp;
struct dirent *dirp;
while ((dirp = readdir(dp)) != NULL) {
if ( isFile(dirp)) {
cout << "IS A FILE!" << endl;
i++;
}
我已经尝试过将dirp-> d_type与(unsigned char)0x8进行比较,但它似乎无法通过不同系统移植.
I've tried comparing dirp->d_type with (unsigned char)0x8, but it seems not portable through differents systems.
推荐答案
您需要在文件上调用stat(2),然后在st_mode上使用S_ISREG宏.
You need to call stat(2) on the file, and then use the S_ISREG macro on st_mode.
类似(改编自此答案):
#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
}
这篇关于如何检查文件是否为常规文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文