CLASS XII: File operations in C++. Appending to files

28.11.12
(Due to off at school on today's theory class, today's lecture is published here for class XII students)

In last class we have encountered a problem that when we re-use same file again in program or while re-run, the previous contents of the file got overwritten. Today we will see how to avoid that by adding contents to same file while preserving its older contents.

With open() we can use parameters, which are also known as 'File Mode Parameters', which can change the mode of opening files in C++ programs.

In order to avoid overwriting older contents of file, we need to open file in 'append' mode, which means it will start inserting new content into the file at the end of older contents in file.

To open file in append mode the parameter to use is: ios::app. (We will discuss ios in later classes).

Here is an example:
In this program in Line 7, with open() ios::app file mode parameter is used
In this output, Output Line 1 "This is QUADD" is input in first run. And Line 2 "And you with best in CS" is input in second run.
Contents of file "ITEM" after First Run

Contents of file "ITEM" after First Run
For any doubts please feel free to ask.

No comments:

Post a Comment