Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ can I reuse fstream to open and write multiple files?

Tags:

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 open(file1, fstream::out | std::ofstream::app) for a each file and close the stream at the end of all 10 files are written.

like image 317
5YrsLaterDBA Avatar asked Feb 17 '10 22:02

5YrsLaterDBA


People also ask

Can you have multiple files open C++?

Using Multiple Files -- C++ It is possible to open more than one file at a time. Simply declare and use a separate stream variable name (fout, fin, fout2, fin2 -- file pointer) for each file.

Can fstream create a file?

To create a file, use either the ofstream or fstream class, and specify the name of the file. To write to the file, use the insertion operator ( << ).

How many files can be opened at the same time in ANSI C?

The C run-time libraries have a 512 limit for the number of files that can be open at any one time.


1 Answers

You will need to close it first, because calling open on an already open stream fails. (Which means the failbit flag is set to true). Note close() flushes, so you don't need to worry about that:

std::ofstream file("1"); // ... file.close(); file.clear(); // clear flags file.open("2"); // ...  // and so on 

Also note, you don't need to close() it the last time; the destructor does that for you (and therefore also flush()'s). This may make a nice utility function:

template <typename Stream> void reopen(Stream& pStream, const char * pFile,             std::ios_base::openmode pMode = ios_base::out) {     pStream.close();     pStream.clear();     pStream.open(pFile, pMode); } 

And you get:

std::ofstream file("1"); // ... reopen(file, "2") // ...  // and so on 
like image 132
GManNickG Avatar answered Sep 23 '22 19:09

GManNickG