Last Updated:

C++. Working with text files

Files allow the user to read large amounts of data directly from the disk without typing them from the keyboard. There are two main types of files: text and binary.

 

Text files are files consisting of any characters. They are organized into lines, each of which ends with a "line end" character. The end of the file itself is indicated by the "end of the file" symbol. When you write information to a text file that can be viewed using any text editor, all data is converted to a character type and stored in character form.

In binary files, information is read and written in the form of blocks of a certain size, in which data of any kind and structure can be stored.

To work with files, special types of data called streams are used. The ifstream is used to work with files in read mode, and ofstream in write mode. To work with files in both write and read mode, use the fstream stream.

In C++ programs, when working with text files, you must connect the iostream and fstream libraries.

In order to write data to a text file, you need to:

  1. Describe a variable of type ofstream.
  2. Open the file using the open function.
  3. output information to a file.
  4. be sure to close the file.

To read data from a text file, you need to:

 
  1. Describe a variable of type ifstream.
  2. Open the file using the open function.
  3. read information from the file, when reading each portion of data, it is necessary to check whether the end of the file is reached.
  4. close the file.

Writing information to a text file

As mentioned earlier, in order to start working with a text file, you need to describe a variable of the ofstream type. For example:

ofstream F;

A variable F is created to write the information to the file. In the next step, you must open the file for writing. In general, the stream opening operator will look like this:

Fopen(«file»mode);

Here, F is a variable described as ofstreamfile is the full name of the file on the disk, and mode is the mode of operation with the file being opened. Note that if you specify the full file name, you need to put a double slash. To access, for example, the accounts.txt file located in the sites folder on drive D, the program must specify: D:\\sites\\accounts.txt.

The file can be opened in one of the following modes:

  • ios::in — open the file in data reader mode; mode is the default mode for ifstream streams;
  • ios::out — open the file in the data recording mode (this destroys information about the existing file); mode is the default mode for ofstream streams;
  • ios::app — open the file in the mode of writing data to the end of the file;
  • ios::ate — move to the end of an already open file;
  • ios::trunc — clear the file, the same happens in ios::out mode;
  • ios::nocreate — do not perform an operation to open a file if it does not exist;
  • ios::noreplace - Do not open an existing file.

The mode parameter may be missing, in which case the file is opened in the default mode for this stream.

After successfully opening the file (in any mode), the variable F will be stored true, otherwise false. This will allow you to verify that the file open operation is correct.

You can open the file (for example, take the file D:\\sites\\accounts.txt) in write mode in one of the following ways:

1
2
3
4
5
6
7
8
9
10
the first ofstream F method
;
F.open("D:\\sites\<strong>\</strong>accounts<strong>.</strong>txt", ios::out);
the second way, the ios::out mode is the default
mode for the ofstream
ofstream F stream;
F.open(«D:\\game\\noobs.txt»);
the third method combines the description of the variable and the type
of stream
and the opening of the file in a single ofstream F statement ("D:\\game\\noobs.txt", ios::out
);

After opening the file in write mode, an empty file will be created into which you can write information.

 

If you want to open an existing file in write mode, you should use the ios::app value as the mode.

After opening a file in recording mode, you can write to it in the same way as on the screen, only instead of the standard cout output device, you must specify the name of the open file.

For example, to write the variable a to stream F, the output statement would be:

F<<a;

For sequential output to the stream G of variables bcd, the output statement becomes as follows:

G<<b<<c<<d;

Closing the stream is carried out using the operator:

F.close();

As an example, consider the following task.

Task 1

Create a text file D:\\sites\\accounts.txt and write n real numbers to it.

Decision

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main()
{
setlocale (LC_ALL, «RUS»);
int i, n;
double a;
Describes a stream for writing data to an ofstream f file
.
open the file in write mode,
ios::out mode is set by default
to f.open("D:\\sites\\accounts.txt", ios::out);
enter the number of real numbers
cout<< "n="; cin>>n;
Loop to enter real numbers
and write them to the for file
(i=0; i<n; i++)
{
cout<< "a=";
enter the number
cin>>a;
f<<a<<"\t";
}
thread
closure f.close();
system(«pause»);
return 0
;
}
 

Reading information from a text file

In order to read information from a text file, you need to describe a variable of type ifstream. After that, you need to open the file for reading using the open statement. If the variable is called F, then the first two statements will be as follows:

1
2
ifstream F;
F.open(«D:\\sites\\accounts.txt», ios::in
);

After opening the file in reading mode, you can read information from it in the same way as from the keyboard, only instead of cin you need to specify the name of the stream from which the data will be read.

For example, to read data from stream F to variable a, the input statement would look like this:

F>>a;

Two numbers in a text editor are considered separated if there is at least one of the characters between them: a space, a tab, a line end character. It is good when the programmer knows in advance how many and what values are stored in the text file. However, often only the type of values stored in the file is known, and their number may vary. To resolve this issue, you must read the values from the file one at a time, and before each read, check whether the end of the file is reached. And the F.eof() function will help to do this. Here, the F-thread name function returns a Boolean value: true or false, depending on whether the end of the file is reached.

Therefore, the loop for reading the contents of the entire file can be written as follows:

1
2
3
4
5
6
7
8
9
organize to read the values from the file, the loop will
be interrupted when we reach the end of the file,
in this case F.eof() will return the truth
while (! F.eof())
{
reading the next value from the F stream to the variable a
F>>a;
then the value of the variable a is processed

}

For better assimilation of the material, consider the task.

Task 2

In the text file D:\\game\\accounts.txt store real numbers, display them on the screen and calculate their number.

Decision

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <iomanip>
#include <stdlib.h>
using namespace std;
int main()
{
setlocale (LC_ALL, «RUS»);
int n=0;
float a;
fstream F;
open the file in F.open reading
mode("D:\\sites\\accounts.txt");
if the file was opened correctly, then
if (F)
{
loop to read values from the file; the loop execution will
be interrupted when we reach the end of the file, in which case F.eof() will return the truth.
while (! F.eof())
{
reading the next value from the F stream to the variable a
F>>a;
displaying the value of the variable a on the screen
cout<<a<<"\t";
Increase the number of n++ reads
.
}
thread closure
F.close();
the display of the number of cout numbers
read<<"n="<<n<<endl;
}
if the file did not open correctly, then display
a message about the absence of such a file
else cout<<" The file does not exist"<<endl;
system(«pause»);
return 0
;
}
 

This is the relatively voluminous lesson on text files. In the next article, we will look at the manipulation methods by which binary files are processed in C++.


Here's a bit of a reworking of one of the examples of this article... It is designed for two lines in the file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
setlocale (LC_ALL, "RUS");
int i, x=0;
string a;
ofstream f;
f.open("noobs.txt", ios::out);
cout<<"To switch to a new line, type *"<<endl;
while (x<2)
{
a='\0′;
while (a!="*")
{
getline(cin, a);
if (a!="*") f<<a<<"\t";
}
f<<endl;
x++;
}
f.close();
system("pause");
return 0;

}

This can be done using the same getline. Here is the code of the program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include "stdafx.h"
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
setlocale (LC_ALL, "RUS");
int i, k=0;
char c[256];
fstream f;
f.open("noobs.txt", ios::in);
while (!f.eof())
{
f.getline(c, 256);
k++;
}
cout<<"In the file "<<k<<" lines(s)";
f.close();
system("pause>>void");
return 0;

 }

Perhaps you are using a variable of type char as a temporary variable? Since if you take the program from the last example and the correctly filled file (spaces between the numbers), then everything should work fine.


If you want to output values using a character variable, you can use several methods, for example, without changing the operators, do the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int n=0;
char a;
fstream F;
F.open("noobs.txt");
if (F)
{
F>>a;
while (F.eof()=='\0′)
{
cout<<a;
F>>a;
n++;
}
F.close();
cout<<"\n n="<<n<<endl;
}
else cout<< "File does not exist"<<endl;

Variables defined by a structural type are written to a file in the same way as regular variables. Here's a case in point:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include "stdafx.h"
#include <iostream>
#include <fstream>
using namespace std;
struct example structure
definition {
int a[3];
char c;
};
example x; define variables of type struct example
void main()
{
ofstream f;
f.open("accounts.txt", ios::out);
cout<<"Symbol >"; cin>>x.c;
f<<x.c<<"\t"; write a variable of type struct example to the for file
(int i=0; i<3; i++)
{
cout<<"mas[" <<i<<"] > "; cin>>x.a[i];
f<<x.a[i]<<"\t"; write a variable of type struct example to the file
}
f.close();
system("pause>>void"
);
}

 

Here's part of the code. I can't figure out the file entry. Could you help me. Can the code be improved. I would be very grateful. Thank you.

 
1
2
3
4
5
6
7
8
9
10
11
int a, b, c;
fstream F;
F.open("out.txt");
while (! F.eof()) F>>a>>b>>c;
F.close();
c=a%b;
a=b;
b=c;
F.open("in.txt", ios::out);
F<<a<<"\t"<<b<<"\t"<<c;
F.close();

Something like this I think will do. You must specify the correct path to the file, which means that in the example it is in the same folder as the project (in Windows, this is approximately the following address: C:\Users\User\Documents\Visual Studio version\Projects\projectname\project_name).