Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The difference between using fstream constructor and open function

Tags:

c++

io

fstream

I have a simple question about the constructor of fstream and the .open function. Are there any differences between the following two expression?

1

fstream("file.txt",ios::app);

2

fstream fin;
fin.open("file.txt",ios::app);

For (1), I don't need to use .open function again right? Any functional differences between the two expression?

My second question is that if I left the openmode empty, what will be the default open mode?

like image 258
jackycflau Avatar asked Oct 07 '15 16:10

jackycflau


1 Answers

There are no differences in terms of the state of the objects following your two snippets.

Why are there two versions?

  1. The ctor exists in order to create fstream objects that are immediately associated with a stream.

  2. The open exists because these types of objects cannot be copied. Hence you cannot assign an fstream object to a different stream by writing:

    fstream foo('bblskd');
    // ...
    foo = fstream('skdjf');
    

(Note that this interface was devised before move semantics).


You can find the default open mode here.

like image 186
Ami Tavory Avatar answered Oct 15 '22 12:10

Ami Tavory