Files, reading, writing, and naming?

Using C++ I know how to write a file and read from it, this site does a good job of explaining how tod do that, however, I was wondering if there was a way in which, I could have my program save the file as a new name each time. In other words, I want to automatically create a new file and not have my previous file overwritten. Ideally it would be named after the current system time. I've tried setting a string variable to the system time and then using that variable as the file name... but I'm not sure if that's even possible.
It should be very possible. Do as you said above and use the string in an ofstrem object;
1
2
3
4
5
std::ofstream oFile( std::string, std::ios::out );

oFile << stuff;

oFile.close();


I've never used it to create files with names I want, but some people in this forum have used c_str();
1
2
3
4
5
6
7
8
9
std::string name;

std::getline( std::cin, name, '\n' );

std::ofstream oFile( name.c_str(), std::ios::out );

oFile << stuff;

oFile.close();


Also, if you want to write to a file and just write to the end of it, i.e. not overwrite, you need to appened to it;
std::ofstream oFile( name, std::ios::out | std::ios::app );
Adding on to the above point (which essentially talks about how you can take in a file name from the user and create a file using the user's input) -

Note that: ofstream oFile( xyz) automatically opens the file. xyz needs to be a CString. That is why we use name.c_str() to convert it to Cstring.

If you are still looking for creating new files each time and naming them after the current system time, I suggest you to go through the below articles. They helped me accomplish the exact same task you are talking about.

http://www.cplusplus.com/reference/clibrary/ctime/
http://www.cplusplus.com/reference/clibrary/ctime/strftime/

Topic archived. No new replies allowed.