我正在使用C fstream来读取配置文件.
#include <fstream> std::ifstream my_file(my_filename);
现在,如果我传递一个目录的路径,它会默默地忽略它.例如.即使my_filename是目录,my_file.good()也会返回true.由于这是我的程序的意外输入,我喜欢检查它,并抛出异常.
如何检查刚刚打开的fstream是常规文件,目录还是流?
我似乎无法找到办法:
>从给定的ifstream获取文件描述符.
>使用其他一些机制在ifstream中查找此信息.
在some forum discussion中,有人认为这两者都不可能,因为这是依赖于操作系统的,因此永远不会成为fstream C标准的一部分.
我能想到的唯一选择是重写我的代码以完全摆脱ifstream并使用文件描述符(* fp)的C方法以及fstat():
#include <stdio.h>
#include <sys/stat.h>
FILE *fp = fopen(my_filename.c_str(),"r");
// skip code to check if fp is not NULL,and if fstat() returns != -1
struct stat fileInfo;
fstat(fileno(fp),&fileInfo);
if (!S_ISREG(fileInfo.st_mode)) {
fclose(fp);
throw std::invalid_argument(std::string("Not a regular file ") + my_filename);
}
我更喜欢fstream.因此,我的问题.
解决方法
void assertGoodFile(const char* fileName) {
ifstream fileOrDir(fileName);
//This will set the fail bit if fileName is a directory (or do nothing if it is already set
fileOrDir.seekg(0,ios::end);
if( !fileOrDir.good()) {
throw BadFile();
};
}