Friday, November 25, 2011

Learn C++ Programming Tutorial Lesson 9 - Reading and writing text and data files


Writing text files

A text file is a file that stores words and sentences in plain text. You must include the fstream.h header file before you can use files. You must then create a ofstream object which will let you open a file and output data to it. When creating the object you must put the name of the file you want to open in brackets. If the file does not exist it will be created and if it already exists it will be cleared.
ofstream f("test.txt");
You write to a file in a similar way as you write to the screen. All you have to do is replace cout with the name of the ofstream object.
f << "Hello";
Use the close method of the ofstream object to close the file when you are finished working with it. If you don't close a file then some data may not be written to it.
f.close();

Appending to files

Files are cleared by default when you open them. If you want to add things to an existing file then you must open it for appending by using ios::app when opening the file.
ofstream f("test.txt",ios::app);

Reading text files

You must declare an ifstream object instead of an ofstream when reading from files.
ifstream f("test.txt");
You need to declare a character array to store the data read when reading from a file. The character array can be any size as long as it is big enough to store what you are reading in.
char s[50];
Reading from a file is similar to using cin. Just replace cin with the name of the ifstream object.
f >> s;

Writing data files

A data file is a file that is usually used to store structures. First we will create a structure called teststruct.
struct teststruct
{
   int a;
   int b;
};

Now let's declare a struct of the teststruct type and set its values.
teststruct ts;
ts.a = 5;
ts.b = 6;

You open a data file in the same way as a text file but you should give the file a .dat extension.
ofstream f("test.dat");
Writing to a data file is a bit more complicated. You must use the write method of the ofstream object. The first parameter of the write method is a pointer to the data structure to be written. The second parameter is the size of the object that you are writing.
f.write((char *)(&ts),sizeof(ts));
Remember to close the file when you are finished writing to it.

Reading data files

To read from a data file we will first create an ifstream object and a structure of the teststructure type.
ifstream f("test.dat");
teststructure ts;

The read method of the ifstream object looks similar to the write method of the ofstream.
f.read((char *)(&ts),sizeof(ts));
You should then test to see if the values were read properly by writing them to the screen.
cout << c.a << endl;
cout << c.b << endl;

0 comments:

Post a Comment

Setec Institute || Group : SH6 | | Name : Kim Chanthy. Powered by Blogger.

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Hot Sonakshi Sinha, Car Price in India