-1

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!

Ryan Haining
  • 35,360
  • 15
  • 114
  • 174
Lil Jakers
  • 77
  • 1
  • 1
  • 4
  • 1
    Also see: [Fastest way to check if a file exist using standard C++/C++11/C?](http://stackoverflow.com/questions/12774207/fastest-way-to-check-if-a-file-exist-using-standard-c-c11-c) – NathanOliver Nov 20 '15 at 17:12
  • Look at this post http://stackoverflow.com/questions/1383617/how-to-check-if-a-file-exists-and-is-readable-in-c – Tequila Nov 20 '15 at 17:26
  • Possible duplicate of [What’s the best way to check if a file exists in C++? (cross platform)](http://stackoverflow.com/questions/268023/what-s-the-best-way-to-check-if-a-file-exists-in-c-cross-platform) – YSC Nov 20 '15 at 17:32

2 Answers2

0

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
    }
}
Domcho
  • 1
  • 2
0

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);
Amit G.
  • 2,546
  • 2
  • 22
  • 30