Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between using ifstream and ofstream with cin and cout

Tags:

c++

I read about fstream, etc., a while ago. It says that ifstream is used to read data from a file, while ofstream is used to write data. I want to know that, what is the essence of using ifstream/ofstream if you can just use cin.getline() to fetch the data and cout << to print those?

like image 460
Sniper30 Avatar asked Dec 13 '14 05:12

Sniper30


1 Answers

ifstream: Stream class to read from files
ofstream: Stream class to write to files

Now what is a file?
Files are resources for storing information. For example, a text file.

Now, let's look at an example which explains ofstream.
Look at the following code:

#include <iostream>
#include <fstream>

using namespace std;

int main () {
     ofstream myfile;
     myfile.open ("example.txt");
     myfile << "Writing this to a file.\n";
     myfile.close();
     return 0;
}

Here, we are writing something to a file. Writing information you can say.

Now, what is the difference between cin/cout and ifstream/ofstream?

cin is an object of class istream and cout is an object of class ostream. And in fact, we can use our file streams the same way we are already used to using cin and cout, with the only difference being that we have to associate these streams with physical files. Just think that cin/cout is a part of istream/ostream that is used for standard input/output.

Hope it helps a bit.

For more information, you can look at this link: Input/output with files.

like image 189
Shubhashis Avatar answered Sep 28 '22 15:09

Shubhashis