The basics of programming in c++ for beginners

Working with files in C ++. Part 1 – Библиотека fstream.

header fstream It provides the functionality to read data from a file and write to the file. In general, it is very similar to the header iostream, who works with the console, because the console is also a file. Therefore, all the basic operations are the same, for small differences, as in the previous topic on iostream.

The most frequent operations following:

    1. Operators Redirection O – << and >>


    1. Methods of recording and reading rows getline() and get() c put()


    1. Streaming read and write methods write() and read()


    1. Public method creation and closing files open() and close()


    1. The methods of verification whether the file is opened is_open() and whether the file end is reached eof()


    1. Setting the formatted output for >> through width() and precision()


  1. positioning operation tellg(), tellp() and seekg(), seekp()

It's not all possibilities, which provides library fstream. Consider all now we do not, since their range of application is narrow enough. Acquainted with the above. Start by reading the class.

class ifstream

It provides opportunities to read files. Open the file in two ways: calling method open() or by entering the path to it in the constructor. You need to prepare a text file, before, start typing the code. On the disc d, create a folder named 1  and in it, create a file with the extension txt – “файл.txt”.

Opening a file in the constructor looks like this:

So we ask to open a file named file.txt txt, which is in the folder with the name 1, and the folder is on drive d.

Using the open method() conveniently, if the programmer does not want to be tied directly to a file. Suddenly you need a class property or global variable, well, then open the file already. If you need to open a file within a certain function, to work with him and to close, you can set the path to the file directly in the constructor. In general, depending on the situation.

opening file, desirable to prescribe by: if he opened? Since there are a number of reasons, on which the file can not be opened, and we do not see. For example, file with the specified name is not in the prescribed folder or path is not valid. You can go two ways: check the file in a variablelogical expression (applying the operator “!”,  for example) or to use the method is_open() :

So everything will work fine and the file will open:

библиотека fstream, work with files in c ++, Programming for beginnersNow try to enter the name of the folder is not 1, and 2 ifstream file ("d:\\<span style="color: #ff0000;"><strong>2</strong>\\файл.txt”); and restart the program. Since the specified folder name, we did not create, then the file, naturally, It can not be opened:

библиотека fstream, work with files in c ++, Programming for beginners

The second embodiment checks using the methodis_open() :

Methodis_open() return 1, If the file is found and successfully opened. otherwise returns 0 and work code prescribed in the block else.

If the file is not open – desirable to handle the error. Usually, if all of the work program associated with the file they write a certain message to the console, and put out of the program. When serious errors common to return a code execution (number),  which will characterize one or another mistake. The codes for each type of error the author of the program can invent their own. One of the ways to handle errors in the program, we have considered in the article Exceptions in c++.

If the file is opened successfully, from it you can read.

read the operator>>

As well as in iostream Reading can be arranged by the operator >>, that indicates in which variable will be made to read:

considers real, string and integer. row readout end, if there was a space or end of line. It is worth noting, that the operator >> It applied to text files. Reading from a binary file to make the best using the method read().

By the way, this statement is quite convenient, if the task is to split the file into words:

Methods getline() и get()

Reading the character string to the translation of the carriage is made the same as in iostream by getline(). Moreover, it is recommended to use the overloaded version of the function, if you read a line of type string:

If you need to read in an array of characters char[], either get() or getline() just as the methods:

The principle is generally the same, as in the analogs of iostream: Shown as a parameter buffer (variable, where the reading will be done), or rather a pointer to a block of memory (if the variable is declared statically: char buffer[255] for example, it is written in the parameters &buffer), specifies the maximum number of readable (in this example n),  so as not to overflow has occurred and the output of the buffer limits and the separator character as required, to which will Proofreading (in this example the gap). I hope I did not hurt tread on the trunk fanatics C, if the soot that these two functions on 99% interchangeable, and 95% They may be replaced by read().

Method read()

Similar to the previous example?

Actually here the same result – It is considered to be a specified number of characters. The exception only, it is impossible to specify the delimiter. read() used for unformatted input. It is intended primarily to read binary files. Since the text file – a special case of a binary, this method is quite applicable to the text file.

Method close()

closes the file. Even nothing to add. Perhaps the only remark – on, that the file, opened for reading, will not be closed by this method usually does not become worse. Very rare situation, when opened for reading deteriorates file, if you complete the program without closing the file. This damage is associated primarily with non-standard devices such as tape drives Tape or what some artful stream of industrial controllers, but in Feng Shui to remember– open file should be closed. It is considered good form.

Method eof()

Checks whether the file end is reached. That is. whether it is possible from it to continue reading. The above example of the proofreading word operator >> just use this check.

Method seekg()

Installs the current position to the desired, indicates the number. This method is also transmitted positioning method:

    • ios_base::end – Read off a new position at the end of the file


    • ios_base::beg – Read off a new position from the beginning of the file (absolute positioning)


  • ios_base::cur – Jump to n bytes from the current position in the file (по умолчанию)

Method tellg()

Sometimes you need to get information about, as already read. This method will help tellg():

It returns a value of type int, which shows how much has already passed in bytes. It can be used in tandem with the method seekg(), To get the file size:

As an example of the binary reading methods can be dismantled so class:

Similar wrapper classes useful, if there are problems reading from a binary whole structure.

Videos about working with files in C ++:

19 thoughts on “Working with files in C ++. Part 1 – Библиотека fstream.

  1. f.seekg(9, ios_base::end);,8);
    file size (in bytes): -1Press any key to continue . . .

  2. What about the method .seekp()? he is also responsible for the idea of ​​some kind of pointer, and there is no disk imaging……

  3. Well, the code-style, pancake. All blocks and arguments is stuck on one another, any gaps, or tab, Only in ReadStream, although, suspect, there was just a piece of neatly stolen. Fortunately though she writings not bydlokod…

  4. I think, proofreading words from a file do better to sell through … while, than through for.

    1. The choice of cycle depends on the operator's knowledge of the number of iterations: if the number is unknown – then it is better to use WHILE, if you know – It recommended FOR (To read in Polyakova. YU., advanced-level textbook).

  5. Sooooo little information. I think, somewhere between 1 and 2 % of the total capacity of PL “C/C++”. We have a lecture at the university is all about telling other methods, much shorter and more convenient. Here are some of them:

    The difference between these two methods is, that getline () retrieves from the flow limiting character (\0), while get () this does not. neither one, no other method does not record the restrictive character in the buffer.

Leave a Reply to Student Cancel reply

Your email address will not be published. Required fields are marked *