【问题标题】:fstream Checking if file exists c++fstream 检查文件是否存在 C++
【发布时间】:2016-02-23 06:32:28
【问题描述】:

大家好,我正在做一个 rpg 项目,我正在创建播放器文件,以便他们保存进度等。

我已经制作了一个测试程序,以便我可以更简单地向您展示我正在寻找的内容

代码:

#include <iostream>
#include <fstream>
#include <string>

int main(){
  std::string PlayerFileName;
  std::cout << "Name Your Player File Name: ";
  std::cin >> PlayerFileName;
  std::ofstream outputFile;
  std::string FileName = "Players/" + PlayerFileName;
  outputFile.open(FileName); // This creates the file

  // ...
}

我想检查 Player 文件名是否已经存在于 Players 目录中,因此人们无法保存他们的进度。

谢谢!

【问题讨论】:

标签: c++ file fstream


【解决方案1】:

我建议以二进制模式打开文件并使用 seekg() 和 tellg() 来计算它的大小。如果大小大于 0 字节,则表示该文件之前已打开并已写入数据:

void checkFile()
{
    long checkBytes;

    myFile.open(fileName, ios::in | ios::out | ios::binary);
    if (!myFile)
    {
        cout << "\n Error opening file.";
        exit(1);
    }

    myFile.seekg(0, ios::end); // put pointer at end of file
    checkBytes = myFile.tellg(); // get file size in bytes, store it in variable "checkBytes";

    if (checkBytes > 0) // if file size is bigger than 0 bytes
    {
        cout << "\n File already exists and has data written in it;
        myFile.close();
    }

    else
    {
        myFile.seekg(0. ios::beg); // put pointer back at beginning
        // write your code here
    }
}

【讨论】:

    【解决方案2】:

    像这样检查文件是否存在:

    inline bool exists (const std::string& filename) {
      struct stat buffer;   
      return (stat (filename.c_str(), &buffer) == 0); 
    }
    
    • 使用这个需要记得#include &lt;sys/stat.h&gt;

    -

    在 C++14 中可以这样使用:

    #include <experimental/filesystem>
    
    bool exist = std::experimental::filesystem::exists(filename);
    

    & 在 C++17 中:(reference)

    #include <filesystem>
    
    bool exist = std::filesystem::exists(filename);
    

    【讨论】:

      猜你喜欢
      • 2014-10-03
      • 1970-01-01
      • 2011-04-07
      • 2013-09-19
      • 2013-06-04
      • 2017-04-24
      • 2015-06-01
      • 1970-01-01
      • 2021-12-25
      相关资源
      最近更新 更多