[CSI] Question on File I/O Declatration and Opening on Same Line

Mikhail Nesterenko mikhail at cs.kent.edu
Wed Mar 16 16:13:00 EDT 2022



> In this example from the PowerPoint on File I/O, why is there no .open
> after the fin stream declaration and opening in the single statement
> example?
> 
> before C++ program can read from or write to a file stream, the stream
> needs to be connected to a file. This is referred to as opening the file:
> fin.open(???myfile.dat???); // opening file
> string declaration and file opening in single statement
> ifstream fin(???myfile.dat???);

You can either declare a stream and then open it (associate with a
file) as two separate statements:

     ofstream fout;  // declaring file stream
     fout.open("myfile.dat"); // opening file

Or as a single combined statement:

     ofstream fout("myfile.dat");

The second version is shorter, but in the first the version, the same
stream may be re-used for multiple files: by successfully opening and
then closing the file.

Thanks,
-- 
Mikhail


More information about the cs13001 mailing list