A basic topic in programming is the processing of files. If information is to be stored until the next program start, this data is written to the hard disk in files. Thus the information remains also after the termination of the program.
After opening a file, it remains locked for further accesses from outside. At this moment, a file can only be processed by the program that opened the file. If you forget to close a file, it remains locked at least until the end of the program. With some operating systems also up to the reboot of the system.
C++ provides the following classes for outputting and inputting characters to and from files:
Objects of the class
fstream are used for file operations. If the file is only written to, the class
ofstream can be used instead. For pure input files, the class
ifstream can be used. Input and output operators (
<<) can be applied to the objects of these classes. Before an access, the file must be opened with the element function
open(). You can also leave the task of opening to the constructor of the
fstream class by passing the file name as a parameter to the object when defining it. After processing the file, it must be closed again with the element function
close(). However, this task is also automatically taken over by the destructor, so that you only have to call
close() if you want to close a file before the object is resolved.
open() expects 2 parameters. First the name of the file to be opened. The second parameter is the mode in which the file will be opened.
|Constant (second parameter of the ||Meaning|
|ios::trunc||File will be emptied when opened|
|ios::app||Append written data to the end|
|ios::ate||Set position pointer to the end|