Generating Output File Names on the fly

Hey everyone, I am stuck and I keep going around in circles.

PROBLEM: I have a program that is reading data from a text file and sorting it into other files, these output files can only be so many lines long befor I need to make another.
QUESTION: How do I generate file names of output files to as I need them?

Pseudo-Code Example:
Entries 1-20 go to File1.
if more exist
Make File2
Entries 21-41 go to File2.
if more exist...

I'm reading thing in fine and sorting them to the file as I need but I cannot figure out how to change the file name after it is full.

Thanks for your help guys.
I've tried changing the value of a pointer that is passed to ofstream and holds the file name, this causes errors when I compile.

I'm thinking of launching the create_file and the sort_data in functions and having those grab the ofstream file name from variables that I change then pass to them when ever the files have reached a certain size.
Just musing, but I would have an integer counter that has the file "number" you are currently on (File1, it would be 1, etc.). Then you can use a stringstream to create the filename like so:

1
2
3
4
5
int file_counter;
// ...
std::stringstream ss;
ss<<"File"<<file_counter;
std::string Filename = ss.str();
I tried something like this, the problem I ran into was that the ofstream didn't change even though the string I passed to it with the file name did. I tried running it as a function and passing the new filename thinking that it would make an output file based on what I feed it but I did a cout inside the function and it still had the origional ouput file name. This is becoming more of a thought excercise for me as I found a work around for the project. There has to be a way I doubt I'm the only one in history who wanted to do this in C\C++.
Last edited on
For anyone who is wondering my workaround sucks but it gets the job done. I kill the stream to the output file then call a function to rename it based on the string I pass to it. When the function returns a success I open the output stream again for the next set of data, if the function fails I run a few checks and respond according to what I find.
Are you sure you are closing the old file before trying to open the new file? If the old file isn't closed, you'll get the problem you're running into.
For my work around? Yeah that works fine I just don't like it. I am wondering about the first thing and I put the workaround in as a foot note.
Topic archived. No new replies allowed.