fstream 检查文件是否存在 c++

fstream Checking if file exists c++

本文关键字:存在 c++ 是否 文件 检查 fstream      更新时间:2023-10-16

大家好,我正在做一个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
  // ...
}

我想检查并查看玩家目录中的玩家文件名是否已存在,以便人们无法保存他们的进度。

谢谢!

我建议以二进制模式打开文件并使用 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
    }
}

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

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

-

在 C++14 中可以使用以下内容:

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

C++17:(参考资料(

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