14

我正在使用 C++ fstream 来读取配置文件。

#include <fstream>
std::ifstream my_file(my_filename);

现在,如果我传递一个目录的路径,它会默默地忽略它。例如my_file.good()返回真,即使my_filename是一个目录。由于这是我的程序的意外输入,我喜欢检查它并抛出异常。

如何检查刚刚打开的 fstream 是否为常规文件、目录或流?

我似乎无法找到一种方法:

  • 从给定的 ifstream 中获取文件描述符。
  • 使用其他机制在 ifstream 中查找此信息。

一些论坛讨论中,有人建议两者都不可能,因为这取决于操作系统,因此永远不可能成为 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。因此,我的问题。

4

4 回答 4

3
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();
   };
}
于 2015-03-27T21:55:42.010 回答
3

从 C++17 开始,我们可以filesystem使用(基于boost::filesystem)。这将比 C++ 中的其他任何东西都更便携(尽管stat()我认为它的效果也很好)。

您有两个可用的函数,一个在需要时返回错误代码。

bool is_regular_file( const path& p );
bool is_regular_file( const path& p, error_code& ec );

您可以将这些与以下内容一起使用:

#include <filesystem>

...
    if(!std::filesystem::is_regular_file(path))
    {
        throw std::runtime_error(path + " was expected to be a regular file.");
    }
...

查找有关cppreference的更多详细信息。

警告:一些编译器说他们有 c++17,但文件系统可能仍然是实验性的;即 GNU C++ 只有自 g++ v8.0 起才有完整版本,有关详细信息,请参阅此问题:Link errors using <filesystem> members in C++17 )

于 2020-06-28T22:24:51.307 回答
2

有不同的方法来解决这个问题:

  1. 忽略它。说真的,如果目录内容作为有效配置通过,我会感到惊讶。如果没有,解析无论如何都会失败,因此您不会冒导入错误数据的风险。此外,您不会阻止用户提供管道或类似的不是文件的东西。
  2. 在打开它之前检查路径。您可以使用stat()或直接使用 Boost.Filesystem 或一些类似的库。我不是 100% 确定 C++11 中是否添加了类似的东西。请注意,这会产生竞争条件,因为在您检查之后但在打开之前,一些攻击者可以使用目录切换文件。
  3. 通常,有一些方法可以从 中检索低级句柄fstream,在您的情况下可能是FILE*. 还有一些方法iostream可以fstreamFILE*. 这些总是特定于实现的扩展,因此您需要一些#ifdef魔法来定制您的代码特定于使用的标准库实现。我敢于依靠他们的存在,即使不是,如果您需要移植到一些无法提供更简单方法的晦涩系统,您仍然可以创建一个streambufon tof of a 。FILE*
于 2015-03-27T21:34:15.827 回答
2

由于 IO 操作的操作系统依赖性,思考很复杂。

我在 OS X 10.10.2、Linux 2.6.32 和 FreeBSD 8.2-RELEASE 上尝试了一些技术(后两个是稍旧的操作系统,我使用了一些旧的 VirtualBox VM)。

  • 我还没有找到万无一失的方法。如果您真的要检查,请stat()在路径上使用,或者使用open()带有fstat().
  • PSkocik 建议的seekg(0, std::ios::beg);方法对我不起作用。
  • 对于 fstreams,最好的方法是打开并从文件中读取,然后等待错误。
  • 为了引发所有必需的异常,必须同时设置badbitAND ,特别是在 OS X 上。failbit例如my_file.exceptions(std::ios::failbit | std::ios::badbit);
  • 这也会在读取常规文件后导致文件结束 (EOF) 异常,这需要代码忽略这些正常异常。
  • my_file.eof()也可能在更严重的错误上设置,因此对EOF条件的检查很差。
  • errno是一个更好的指标:如果引发异常,但errno仍为 0,则很可能是一个EOF条件。
  • 这并非总是如此。在 FreeBSD 8.2 上,打开目录路径只会返回二进制 gobbledygook,而不会引发异常。

这是似乎在我测试过的 3 个平台上处理它的一些合理的实现。

#include < iostream>
#include < fstream>
#include < cerrno>
#include < cstring>

int main(int argc, char *argv[]) {
   for (int i = 1; i < argc; i++) {

      std::ifstream my_file;
      try {
         // Ensure that my_file throws an exception if the fail or bad bit is set.
         my_file.exceptions(std::ios::failbit | std::ios::badbit);
         std::cout << "Read file '" << argv[i] << "'" << std::endl;
         my_file.open(argv[i]);
         my_file.seekg(0, std::ios::end);
      } catch (std::ios_base::failure& err) {
         std::cerr << "  Exception during open(): " << argv[i] << ": " << strerror(errno) << std::endl;
         continue;
      }
      
      try {
         errno = 0; // reset errno before I/O operation.
         std::string line;
         while (std::getline(my_file, line))
         {
            std::cout << "  read line" << std::endl;
            // ...
         }
      } catch (std::ios_base::failure& err) {
         if (errno == 0) {
            std::cerr << "  Exception during read(), but errno is 0. No real error." << std::endl;
            continue; // exception is likely raised due to EOF, no real error.
         }
         std::cerr << "  Exception during read(): " << argv[i] << ": " << strerror(errno) << std::endl;
      }
   }
}
于 2015-03-28T00:37:35.103 回答