About fstream

I just starting studying C++ I/O and i have a question.
If i can use fstream to both read an write from/to files, why exist the other two classes: ofstream and ifstream?

Thank you very much!
I prefer std::ifstream and std::ofstream because I don't have to pass flags like std::ios::in and std::ios::out. There is also no chance I accidentally use read operations when using std::ofstream or write operations when using std::ifstream.
So, I can conclude that it is best not to use fstream, right?
Using them, you can refer to a stream that can only be read from or written to, not both. As an example, consider "cin" which can only be read from, not written to. Presumably you might have a file stream like that, and in that case an fstream would be inappropriate.
Using fstream, I do not need to use the close () after a read or write operation to another read or write operation?
Why would you close a file you aren't done reading (or writing)?

It is okay to use fstream, but the point is that it is rare to perform both input and output on a file at the same time. It is typically better to stick to reading a file or writing a file at any one time. So, use ifstream or ofstream and get the benefits of code that watches you to not do the wrong thing with your file.

Hope this helps.
Okay.
For example, if i open a file for read operation using ifstream and then to write this file using ofstream, I'll always have to use close () before, right?
Ah, Yes, that's correct.

Unless you are doing something extra-tricky, that is also the correct way to do it.


For example, a common beginner's question is how to delete a line from a text file.
Best method?

(1) Read the entire file into a std::deque<std::string>.
(2) Delete the nth line/element of the deque.
(3) Write the entire thing back to the file (overwriting the original data).

Hope this helps.
Last edited on
Okay, so to complete, fstream I have freedom to both read and write to the file in the same operation without using the close (), for example if I open a file with fstream used the default constructor and want to read first, then the writing , I will not have to use the close ()?
No, you cannot both read and write in the same operation. You either read or you write -- they are separate operations.

An fstream will allow you to read and to write to the file without first closing it.

So this statement and example that I saw on a site is correct?

"The file streams we discussed have a limitation(ifstream and osftream) , they can only do input or output at a time. fstream provides us with a way to read, write randomly without having to close and reopen the file:"
1
2
3
4
5
6
7
void main()
{
    fstream file;
    file.open("file.ext",iso::in|ios::out)
    //do an input or output here
    file.close();
}

Last edited on
closed account (Dy7SLyTq)
yes
thank you all guys
Last edited on
Topic archived. No new replies allowed.