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

3

2 Answers 2

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
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.