C++: file reading and writing

Firstly, everything you do before, do not forget to import “<fstream>”.

1
include <fstream>

Three common operations in “<fstream>”

As a noob in C++, I will only introduce these three in this post. If I am gonna be in higher level someday, I will write down more about them, even whole thing.

1
2
3
ofstream   //write
ifstream //read
fstream //write and read

Open a File

In class “<fstream>”, there is an inner function open(), which is work on it through ofstream, ifstream and fstream objects.

1
f.open(filename, mode, prot)

There are three parameters in this function, first one is the filename, second is the way to open it( more..) and third one is the character of the file( unusual using).

Here, I would like to say a little bit more about class “<ios>”.

ios::in open a file for input
ios::out open a file for output
ios::ate initial position: end of the file
ios::app output in the end of the file
ios::binary open a file via binary

Normally, we use them in combination. So, we do this way:

1
2
fstream f;
f.open("test.txt", ios::in|ios::out|ios::binary)

Otherwise, here is also a default way without function open(), cpp has prepare it in . We can use them directly:

1
2
3
ofstream out("...", ios::out);
ifstream in("...", ios::in);
fstream foi("...", ios::in|ios::out);

Close a File

As open() function, here is also a function for closing, which is close().

After closing, the original object can open another file.

1
2
3
4
5
6
ofstream of;
of.open("hello.txt");
of.close();
of.open("hi.txt");
...
of.close();

Reading and Writing on txt file

Read

Same as outputting in the terminal, we can also use << to write the data into a file. (Extension: end of the post)

1
2
3
4
5
6
7
8
9
10
11
12
void openFile(string fileName){
string data;
ifstream in;
in.open(fileName.c_str());
if(in.is_open()){
while(!in.eof()){
string line;
getline(in, line);
cout<<line<<endl;
}
}
}

Write

Using >> as well…

1
2
3
4
5
6
7
8
9
10
11
12
void writeFile(string fileName)
{
ofstream out;
out.open(fileName);
if(out.is_open()){
out<<"test1\n";
out<<"test2\n";

out.close();
}

}

Extension

About cin.ignore(), it is used when you wanna ignore the last input in the terminal. Usually, the first input may effects the next one. It is a solution for that problem, it will clear everything after enter including enter.

1
2
3
4
5
6
7
8
9
10
11
#include<iostream>  
using namespace std;
int main()
{
char str1[30],str2[30],str3[30];
cout << "Name:";
cin>>str1;
cout<<"Address:";
cin.ignore();
cin.getline(str2,30,'a');
cout<<str2;

Thanks for your reading. I am happy, if it is useful for you.


END

Illustrator / Cagy

Text / Cagy

Editor / Cagy

Design / Cagy