Handling files in C ++

The program creates an object of the ifstream class to open the file called Tests.txt using the class constructor and specifying the ios :: noreplace flag that prevents the file from being overwritten. If for some reason an error occurs when opening the file, the error message specified in line 16 is generated. In the absence of errors, the program enters a while loop, which is evaluated by effect of the member function eof () in such a way that the loop runs until you find the end of the file. Using the getline () member function, a line of text is obtained and displayed on the screen, line 21, then we use a conditional instruction if with the module operator (%) to determine if 24 lines of text have been read. Each time the line counter divided by 24 results in a residue of zero, the program stops allowing you to read the previous 24 lines of text. To continue you must press the enter key and then the program will read and display on the screen the following 24 lines of text, lines 22 through 26.

Analyzing the success of file I / O

In the program archiv03.cpp the member functions fail () was used to determine the success of the operation of opening the file Tests.txt. The fail () member function produces the value of 1 if an error occurs in the file operation. Similarly it is advisable to use other functions to verify not only the file opening but also the read and write operations, the member functions that allow us these tests are the following:

good Produces a 1 if the previous operation was successful.

eof Produce a 1 if the end of the file is found.

fail Produce a 1 if an error occurs.

bad Produces a 1 if an invalid operation is performed.

Three of the four functions listed are shown in the following program called archiv04.cpp which copies the contents of the file called Tests.txt into one called Copia.txt. First, an object of the ifstream class called origin is created, which is used to open the file Pruebas.txt for read operations. The member function source.fail () indicates the existence of an error, if it exists. a message is displayed on the screen and the program ends. If the opening of the file Pruebas.txt was successful, we proceed to the next part of the program where an object of the ofstream class called destination is created for write operations which specifies that the file to be created will be called Copia.txt and in agreement to the flag ios :: noreplace, if there is a document with the name of Copia.txt the constructor function will fail, this process is detected by the member function destino.fail () by displaying a message on the screen and ending the program. archiv04.cpp is a program used to copy a file based on ASCII characters.

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 !!