Programming Taskbook

Russian

E-mail:

Password:

User registration   Restore password

1000 training tasks on programming

©  M. E. Abramyan, 1998–2010

 

Examples | C++ | File processing

PrevNext


File processing

Solutions of tasks connected with processing of binary files with numeric data and also string files and text files are described on this page.

Binary file with numeric data: File48

This section contains description of solving the following task:

File48°. Three files of integers called SA, SB, SC and a string SD are given. All given files are of the same size. Create a new file called SD; this file must contain triples of components of the given files as follows: A1B1C1, A2B2C2, ... .

Creating a template and acquaintance with the task

To create a template of the required task one should use PT4Load tool. The solution of the task should be entered in the Solve function, which is defined in the File48.cpp file (this file is created by PT4Load tool):

void Solve()
{
  Task("File48");
}

When the program is launched you will see the Programming Taskbook window:

The first line of the input data panel contains four file names: SA, SB, and SC for input files, SD for an output file. The next three lines of the input data panel displays components of the input files. File components are light-cyan colored to distinguish them from standard input-output data and comments. With mouse or keyboard you can scroll the file components .

All input files are created with new name and data for each test running of the program. When the program finishes all files are removed automatically from the working directory.

The running of our program is considered as acquaintance running because the program does not perform input-output operations. In the panel of results the "Example of right solution" tab is active; this tab displays components that should be saved in the output file.

Initial data input

To file processing we shall use stream classes implemented in the standard C++ library rather than input-output function (such as fopen or printf) from the C library. Therefore we should add the following directive in the File48.cpp file:

#include <fstream>

Before solving the task it is necessary to input file names and open file streams:

void Solve()
{
  Task("File48");
  fstream* f = new fstream[4];
  int i;
  for (i = 0; i < 3; i++)
  {
    string s;
    pt >> s;
    f[i].open(s.c_str(), ios_base::binary | ios_base::in);
  }
  delete[] f;
}

Because we input only three file names, the next program running will lead to the error message "Some required data are not input.". To correct the last error it is enough to replace 3 by 4 in the for statement. Now data input is performed correctly, but the program does not create an output file. Therefore we shall see the following message: "Output file is not found".

Note that an run-time error occurs when the open method is called for the fourth file because the ios_base::in mode is not available for non-existing file. But in C++ this error does not lead to the abnormal termination of the program.

Remark. For storing the file name a variable of the char* or char[N] type may be used, for example,

  char s[13];

In this case we can use the s variable as the first parameter of the open method (without call of the c_str method). It is enough to allocate 13 elements for the s array because all file names in Programming Taskbook satisfy the requirements of the "8.3" format (no more than 8 characters for name and no more than 3 characters for extension), therefore the maximal length of file name is 12 characters (the 13th element must be reserved for the zero character that terminates any C-string).

The char[13] type will be also used in programs of the next section.

Creating an empty output file

To avoid the run-time error you should open a non-existing file in the ios_base::out mode. Furthermore, you should close all files at the end of the program:

void Solve()
{
  Task("File48");
  fstream *f = new fstream[4];
  int i;
  for (i = 0; i < 4; i++)
  {
    string s;
    pt >> s;
    if (i < 3)
      f[i].open(s.c_str(), ios_base::binary | ios_base::in);
    else
      f[i].open(s.c_str(), ios_base::binary | ios_base::out);
  }
  /* */
  for (i = 0; i < 4; i++)
    f[i].close();
  delete[] f;
}

The /* */ comment marks the program position, where we can execute input-output file operations: files are already opened by the open method and are not closed by the close method.

Running of this program provides creation of an output file. But this file will be empty, that is, will contain no elements. Therefore we shall see the error message "Wrong solution", and the output data panel will contain the following text:

EOF:

This text (EOF—End Of File) means that the output file exists but contains no elements.

Using of wrong type for file components

We did not use file input-output operations so far. Therefore we did not specify a type for file components.

But if the program contains file input-output operations then it is important to specify the type of file components correctly, otherwise "strange" errors will occurs during the program running. Let's model this situation in our program. For this purpose we replace the /* */ comment by the following statements:

for (i = 0; i < 3; i++)
{
  double x;
  f[i].read((char *)&x, sizeof(x));
  f[3].write((char *)&x, sizeof(x));
}
The given statements provide reading one component from each input file and writing these components to the output file (in the required order). Note that we have specified the component type incorrectly (as double), but the program will be compiled successfully, and it will execute without run-time errors.

The result of the program execution will be unexpected: the output file will contain six components, that is, two components of each input file. It can be explained as follows. In our program the file elements are assumed to be real numbers (of size 8 bytes). But in fact the input files contains integer components (of size 4 bytes). Therefore reading and writing of one "real-valued" component leads to reading/writing of two integer components.

Thus, we see that the errors connected with the incorrect file types are not detected by compiler and do not usually lead to the run-time errors, but often lead to "strange" results.

After replacing the "double" specifier by the "int" one in declaration of the x variable our program will work quite "clearly": the output file will contain three components, that is, one initial component of each input file.

Correct solution, its testing and browsing results

At last, let's present a correct algorithm for the File48 task:

void Solve()
{
  Task("File48");
  fstream *f = new fstream[4];
  int i;
  for (i = 0; i < 4; i++)
  {
    string s;
    pt >> s;
    if (i < 3)
      f[i].open(s.c_str(), ios_base::binary | ios_base::in);
    else
      f[i].open(s.c_str(), ios_base::binary | ios_base::out);
  }
  while (f[0].peek() != -1)
    for (i = 0; i < 3; i++)
    {
      int x;
      f[i].read((char *)&x, sizeof(x));
      f[3].write((char *)&x, sizeof(x));
    }
  for (i = 0; i < 4; i++)
    f[i].close();
  delete[] f;
}

This algorithm contains the "while" loop that provides reading all components from the input files (recall that all input files are of the same size). After running the program we shall see the message "Right solution. The test 1 of 5", and after 5 test runnings we shall receive the message "The task is solved!".

Using the PT4Results tool we can browse information about all test runnings of our program:

File48     c03/05 17:49 Acquaintance with the task.
File48     c03/05 17:52 Some required data are not input.
File48     c03/05 17:55 Output file is not found.
File48     c03/05 17:58 Wrong solution.--3
File48     c03/05 18:02 The task is solved!

String binary files and text files: File67, Text21

In this section we shall discuss some features of processing of string files (i.e., binary typed files with random access) and text files.

String files

Let's consider the File67 task as an example of task with string file processing:

File67°. A file of strings is given. The file contains dates in the "day/month/year" format, the "day" and "month" fields contain two digits, the "year" field contains four digits (for example, "16/04/2001"). Create two new files and write integer values of days and months for each date from the given file to the first and second resulting file respectively (in the same order).

If Programming taskbook is used for task solution in C++ then binary string files are assumed to contain string components of the 80 bytes length. Therefore variables used for file input-output operations must have char[80] type.

Taking into account the feature mentioned above we can solve the File67 task as follows:

#include <fstream>
void Solve()
{
  Task("File67");
  ifstream f;
  ofstream f1, f2;
  char s[13], s1[13], s2[13], x[80], a[3];
  pt >> s >> s1 >> s2;
  f.open(s, ios_base::binary);
  f1.open(s1, ios_base::binary);
  f2.open(s2, ios_base::binary);
  while (f.peek() != -1)
  {
    f.read((char *)&x, sizeof(x));
    strncpy(a, x, 2);
    int n = atoi(a);
    f1.write((char *)&n, sizeof(n));
    strncpy(a, &x[3], 2);
    n = atoi(a);
    f2.write((char *)&n, sizeof(n));
  }
  f.close();
  f1.close();
  f2.close();
}

Text files

Let's consider the Text21 task as an example of task with text file processing:

Text21°. Given a text file that contains more than three lines, remove its last three lines.

Text files, unlike binary string files, cannot be open for reading and writing simultaneously, therefore it is necessary to use an temporary file for text file changing: the required output data should be written to the temporary file, after that the initial file should be removed and the temporary file name should be changed to the initial file name. Lines of the text file are of various length, therefore it is necessary to read all lines to determine the amount of lines in the text file. To read data from the text files one should use the getline method (instead of the read method, which is intended for data reading from the binary files). In all tasks text files are assumed to contain text lines of no more than 79 characters length.

Considering all features mentioned above we can solve the Text21 task as follows:

#include <fstream>
void Solve()
{
  Task("Text21");
  ifstream f1;
  ofstream f2;
  char s[80], s1[13], s2[10] = "$T21$.tmp";
  int n = 0;
  pt >> s1;
  f1.open(s1);
  f2.open(s2);
  while (f1.peek() != -1)
  {
    f1.getline(s, 80);
    n++;
  }
  f1.clear();
  f1.seekg(0);
  for (int i = 0; i < n - 3; i++)
  {
    f1.getline(s, 80);
    f2 << s << endl;
  }
  f1.close();
  f2.close();
  remove(s1);
  rename(s2, s1);
}

This algorithm is inefficient because it requires to read the initial file twice: the first time to determine the amount of file lines, the second time to create an temporary file that will contain all lines of the initial file except three last ones.

The Text21 task can be solved using only one reading of the initial file. In this solution we'll take into account the following consideration: a text line should be written to an temporary file if at least three lines follow this line in the file. This way of solution does not requires to determine the amount of the text lines. To store strings, which have been read from the input file but still have not been written to the temporary file, we shall use an array of three elements of the char[80] type.

We obtain the second, one-pass algorithm of the Text23 solution:

#include <fstream>
void Solve()
{
  Task("Text21");
  ifstream f1;
  ofstream f2;
  char s[3][80], s1[13], s2[10] = "$T21$.tmp";
  pt >> s1;
  f1.open(s1);
  f2.open(s2);
  for (int i = 0; i < 3; i++)
    f1.getline(s[i], 80);
  int n = 0;
  while (f1.peek() != -1)
  {
    f2 << s[n] << endl;
    f1.getline(s[n], 80);
    n = (n + 1) % 3;
  }
  f1.close();
  f2.close();
  remove(s1);
  rename(s2, s1);
}

PrevNext

 

 

Designed by
M. E. Abramyan and V. N. Braguilevsky

Last revised:
02.05.2010