0

I'm trying to write HTML output file. The file is written and all is well, but I'd like to know if there is a way to take a string with it's file name, check if that exists and if yes then change that string somehow. So I would never overwrite already existing file.

string outputFile;
cin>>outputFile;
ofstream out;
string path ="..\\data\\"+ outputFile+ ".html";
out.open(path.c_str());

So in this case if outputFile is let's say "Jesus" then I want to do something so if I would run this 3 times I'd have something like Jesus.html, Jesus2.html, Jesus3.html. Doesn't necesarilly have to be numbered like that, just any change to that string will do. Is this even possible? I tried this using tmpnam() but I don't really understand how it's supposed to work and if it can even be used.

Thanks for any help

0

1 Answer 1

1

you could check if the file exists with one of the methods mentioned here:

Fastest way to check if a file exist using standard C++/C++11/C?

The complete code would look like this

inline bool file_exists (const std::string& name) {
  struct stat buffer;   
  return (stat (name.c_str(), &buffer) == 0); 
}

while (file_exists(file_name))
    file_name += "_1";
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.