I have 10 files need to be open for write in sequence. Can I have one fstream to do this? Do I need to do anything special (except flush()) in between each file or just call
Yes, but you must to close the fstream each time before opening the next file with it.
However, it's better to use a new scoped fstream object for each file access to take advantage of the constructor and destructor behaviors:
struct {
const char *filename;
void (*operation)(fstream&);
} filelist[] = {
{ "file1", callback1 },
{ "file2", callback2 },
...
{ "file10", callback10 },
};
for (int i = 0; i < 10; ++i) {
fstream f(filelist[i].filename);
filelist[i].operation(f);
}
In the code sample above, the fstream is flushed and closed each time through the for loop because the destructor is called when the object loses scope. The fstream is passed by reference to a callback function so that the operations can be handled on a per file basis without a nasty switch statement. If the operation is the same for each file, then that construct can be eliminated.