Handling files in C ++

File opening modes

By specifying the opening of a file as shown in the previous programs, the program overwrites any existing file named Data.txt in the working directory of the program. Depending on the purpose of the program it may be necessary to add data to those already existing in the file, or it may be necessary that the operations of the program are not carried out in case the specified file exists on the disk, for these cases we can specify the opening mode of the file including an additional parameter in the constructor, any of the following:

ios :: app Add-on operations.

ios :: ate Place the file pointer at the end of it.

ios :: in Read operations. This is the default option for objects in the ifstream class.

ios :: out Write operations. This is the default option for objects of the ofstream class.

ios :: nocreate If the file does not exist, the operation is suspended.

ios :: noreplace Create a file, if one exists with the same name, the operation is suspended.

ios :: trunc Create a file, if there is one with the same name, delete it.

ios :: binary Binary operations.

In this way, we can modify the opening mode of the program archiv02.cpp so that the program data is concatenated in the file Datos.txt simply by writing the constructor like this: ofstream file (“Datos.txt”, ios :: app); . If we want the program not to overwrite an existing file we specify the constructor in this way: ofstream file (“Datos.txt”, ios :: noreplace) ;. By using the open mode specifiers you can get more control in file I / O operations.

[ Back to the start ]

File reading operations

To open a file and perform read operations, an object of the ifstream class is created and the procedure is practically the same as that explained in the previous section. After opening the file you can read its contents using the member functions of the ifstream class or the extraction operator. When a file is read, it is usually started at the beginning of the file and its contents will be read until the end of the file is found. To determine if the end of the file has been reached, the member function eof can be used as a condition of a while loop. You can also use the fail member function to detect an error when opening the file, this is demonstrated in the following program, archiv03.cpp:

You may also like...

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

error: Content is protected !!