简体   繁体   中英

fstream Checking if file exists c++

Hi guys I am working on an rpg project and I am creating player files so they can save their progress and such.

I've made a test program so I can show you on a more simple scale of what I am looking for

Code:

#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

  // ...
}

I want to check and see if the Player File Name already exists the the Players directory so people cant save over their progress.

Thanks!

I suggest opening the file in binary mode and using seekg() and tellg() to count it's size. If the size is bigger than 0 bytes this means that the file has been opened before and has data written in it:

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
    }
}

Check if file exists like this:

inline bool exists (const std::string& filename) {
  struct stat buffer;   
  return (stat (filename.c_str(), &buffer) == 0); 
}
  • Using this needs to remember to #include <sys/stat.h> .

-

In C++14 it is possible to use this:

#include <experimental/filesystem>

bool exist = std::experimental::filesystem::exists(filename);

& in C++17: ( reference )

#include <filesystem>

bool exist = std::filesystem::exists(filename);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM