c – 检查fstream是文件还是目录

前端之家收集整理的这篇文章主要介绍了c – 检查fstream是文件还是目录前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用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();
   };
}
原文链接:https://www.f2er.com/c/118236.html

猜你在找的C&C++相关文章