Opening multiple files for writing

Hi,

I am new to C++, I am using it for a small project where I need to sort data and output it to multiple different files for further processing.

I am trying to create and open a number of files, which may change between runs. The files don't need clever names, just something like "dump001.dat", "dump002.dat", etc.

I was hoping to do something like:

1
2
3
4
5
6
7
8
9
std::string filename;
ifstream myfile;
for (int i=0; i!=totalnumber; ++i)
{
    filename = "dumpfile" + i+1 + ".dat" ;
    myfile.open(filename);
}
// code to read in data
// more code to put data into the relevant output file 


This gives me a world of errors and I don't really know why.
Any help would be greatly appreciated!!!
Thanks in advance.

Edit: I missed the semicolons, there were there in my code though!
Last edited on
it's line 5. You can't just concantanate strings and ints together like that.

try
filename = "dumpfile" + std::to_string(i) + ".dat";

if you want "001", "002" you'll have to format it as well.
Last edited on
Thanks mutexe!
how do I then pickout a specific file later on? is it as simple as:
 
dump_file1 << "blah blah blah" 

?
If i understand what you're asking (and i'm not sure I am!), you could, after line6, add the file name to a std::vector<std::string> collection.
That way you can do what you want with them, iterate over the whole collection or search for a specific filename string.
I the code i am basically writing is to bin large amounts of data into smaller files that can be loaded into memory, with each bin being handled separately.
for example with 2 files, 'file1.dat' & 'file2.dat' and read in int 'x'
1
2
3
4
5
if (x < 10) {
  file1.dat << x;
} else { 
  file2.dat << x;
}


These files will then be read in and post processed by an old code we've already got written.

I hope that's a little clearer without going into all the detail?
Thanks,
You'll need one stream object per file you want to write to then (i think).
perhaps it would be better to keep an array of ostreams rather than filename strings then..
Thanks mutexe, I don't really understand what you mean by that, could you explain it a tad more?
well this from your first post:

1
2
3
4
5
6
7
std::string filename;
ifstream myfile;
for (int i=0; i!=totalnumber; ++i)
{
    filename = "dumpfile" + i+1 + ".dat" ;
    myfile.open(filename);
}


will indeed open a number of files. but the way you'd write to a file normally would be something like:

 
myfile << "This is a line.\n";


i.e. you get to the file via the stream object. So i'm guessing (although if someone could clarify/confirm/correct that would be good) that your 'myFile' stream would be associated with the last file created in your for loop.

You would effectively have a bunch of "dangling" files with no stream to get to them through, apart from the last one you open.
Last edited on
Topic archived. No new replies allowed.