C++ PROGRAMMING EBOOK LESSON 9 – READING AND WRITING TEXT AND DATA FILES
A book enter is a enter that stores book and sentences in stark text. You staleness allow the fstream.h brick enter before you crapper ingest files. You staleness then create a ofstream goal which module permit you unstoppered a enter and production accumulation to it. When creating the goal you staleness place the study of the enter you poverty to unstoppered in brackets. If the enter does not subsist it module be created and if it already exists it module be cleared.
ofstream f("test.txt");
You indite to a enter in a kindred artefact as you indite to the screen. All you hit to do is change cout with the study of the ofstream object.
f << "Hello";
Use the near method of the ofstream goal to near the enter when you are ended employed with it. If you don’t near a enter then whatever accumulation haw not be cursive to it.
f.close();
Appending to files
Files are unwooded by choice when you unstoppered them. If you poverty to add things to an existing enter then you staleness unstoppered it for appending by using ios::app when inaugural the file.
ofstream f("test.txt",ios::app);
Reading book files
You staleness tell an ifstream goal instead of an ofstream when datum from files.
ifstream f("test.txt");
You requirement to tell a case clothing to accumulation the accumulation feature when datum from a file. The case clothing crapper be some filler as daylong as it is bounteous sufficiency to accumulation what you are datum in.
burn s[50];
Reading from a enter is kindred to using cin. Just change cin with the study of the ifstream object.
f >> s;
Writing accumulation files
A accumulation enter is a enter that is commonly utilised to accumulation structures. First we module create a scheme titled teststruct.
struct teststruct
{
int a;
int b;
};
Now let’s tell a struct of the teststruct identify and ordered its values.
teststruct ts;
ts.a = 5;
ts.b = 6;
You unstoppered a accumulation enter in the aforementioned artefact as a book enter but you should provide the enter a .dat extension.
ofstream f("test.dat");
Writing to a accumulation enter is a taste more complicated. You staleness ingest the indite method of the ofstream object. The prototypal constant of the indite method is a indicator to the accumulation scheme to be written. The ordinal constant is the filler of the goal that you are writing.
f.write((char *)(&ts),sizeof(ts));
Remember to near the enter when you are ended composition to it.
Reading accumulation files
To feature from a accumulation enter we module prototypal create an ifstream goal and a scheme of the teststructure type.
ifstream f("test.dat");
teststructure ts;
The feature method of the ifstream goal looks kindred to the indite method of the ofstream.
f.read((char *)(&ts),sizeof(ts));
You should then effort to wager if the values were feature right by composition them to the screen.
cout << c.a << endl;
cout << c.b << endl;