C++. Examples of using C++ tools for working with files




Examples of using C++ tools for working with files

The topic provides examples of using the C++ file system for:

  • reading information from files;
  • write information to files.

Contents


Search other websites:

1. A function that reads lines from the keyboard and writes them to a file
#include <iostream>
#include <fstream>
using namespace std;

// The function reads lines from the keyboard and writes them to a file.
void Example1(const char * filename)
{
  ofstream os(filename); // text file for output

  // check if the file is open
  if (!os)
  {
    cout << "Cannot open the file to output. \n";
    return;
  }

  char str[80];

  cout << "Save the lines to HDD. Enter ! to stop." << endl;

  do
  {
    cout << ":";

    // reading a line using spaces between words
    cin.getline(str, 80);

    os << str << endl; // write the string str to the file
  } while (*str != '!'); // end of input - string !

  os.close(); // close the file
  return;
}

void main()
{
  Example1("myfile.txt");
}

After calling the function Example1(), the file “myfile.txt” will be created, in which the lines entered from the keyboard will be written.

The result of the program:

Save the lines to HDD. Enter ! to stop.
:Hello world!
:bestprog.net
:Working with files in C++
:!

 

2. A function that reads a text file and displays its contents on the screen

The Example2() function reads the contents of the file filename, whose name is the input parameter to the function.

#include <iostream>
#include <fstream>
using namespace std;

// A function that reads the file filename and displays it on the screen

// The ifstream class is used to read a file.
bool Example2(const char * filename)
{
  // create an instance of the class
  ifstream is(filename); // open the file in the constructor

  // if the file is not open, then exit with the code false
  if (!is)
    return false;

  // reading lines in a while loop
  char str[100]; // buffer for reading one line

  while (is) // if is nonzero, then the end of the file is not yet
  {
    is.getline(str, 100); // read a line from a file into the buffer str
    cout << str << endl; // display on the screen
  }

  is.close(); // close the file
  return true;
}

void main()
{
  Example2("myfile.txt");
}

The result of the program displays the contents of the file “myfile.txt” created in paragraph 1 of this topic

Hello world!
bestprog.net
Working with files in C++
!

 

3. An example of formatless input/output. Copy one file to another

The example implements the function Example3(), which copies files in binary format. The function takes two parameters. The first parameter of type const char* is the name of the source file. The second parameter of type const char* is the name of the destination file.

The function implements character-by-character copying. To get a character from the source file, use the get() function.

#include <iostream>
#include <fstream>
using namespace std;

// Formatless input/output, copying one file to another file
// The function reads the readFile and writes it to the writeFile
// uses the get() function to read
bool Example3(const char * readFile, const char * writeFile)
{
  // create instances of ifstream and ofstream classes
  ifstream rf(readFile, ios::in | ios::binary); // source file (reading)

  if (!rf)
  {
    cout << "Cannot open source file." << endl;
    return false;
  }

  // create instance of destination file (writing)
  ofstream wf(writeFile, ios::out | ios::binary);

  // if none of the files is open, then exit
  if (!wf)
  {
    rf.close(); // close the source file
    cout << "Cannot open destination file." << endl;
    return false;
  }

  char sym;

  // the loop of character by character reading
  while (rf)
  {
    rf.get(sym); // read rf => sym
    if (rf)
      wf << sym; // write sym => wf
  }

  cout << "Copy result: OK!" << endl;
  rf.close(); // close both files
  wf.close();
}

The call Example3() function from the main() function can be as follows:

void main()
{
  Example3("myfile.txt", "myfile2.txt");
}

After executing the Example3() function, the file “myfile2.txt” will be created, which will be a copy of the file “myfile.txt”.

 

4. An example of formatless input/output. Copying one file to another. Function put()

The Example4() function from this example works the same as the previous one, only the put() function is used instead of output to the stream <<. Also, using the is_open() function, a check is performed to ensure that the file is opened correctly.

#include <iostream>
#include <fstream>
using namespace std;

// Same as Example3(), for write use only put function
bool Example4(const char * readFile, const char * writeFile)
{
  ifstream rf(readFile, ios::in | ios::binary);

  // check if the file is open
  if (!rf.is_open())
    return false;

  ofstream wf(writeFile, ios::out | ios::binary);

  // check if the file is open
  if (!wf.is_open())
  {
    rf.close(); // close a previously opened file rf
    return false;
  }

  char sym;

  // the loop of character by character reading
  while (rf)
  {
    rf.get(sym); // read rf => sym
    if (rf) wf.put(sym); // write sym => wf
  }

  rf.close(); // close both files
  wf.close();
}

void main()
{
  Example4("myfile.txt", "myfile2.txt");
}

 

5. Example function writing a structural variable to a file

In this example, you can implement your own functions that will write structures or classes to a file.

The Example5() function is implemented, which writes a structure variable of type BOOK to a file whose name is an input parameter. The Example5() function uses the write() function to write. The file is opened in binary format (ios::binary).

#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;

// A function that writes a structure of type BOOK to a file,
// it uses write() function
struct BOOK
{
  char title[100]; // title of the book
  char author[70]; // author
  int year; // year of issue
  float price; // book cost
};

bool Example5(const char * filename)
{
  // create a structure
  BOOK B;
  strcpy_s(B.title, "Title of book");
  strcpy_s(B.author, "Authof of book");
  B.year = 2000;
  B.price = 12.65f;

  // create an instance of a file in binary format (ios::binary)
  ofstream outFile(filename, ios::out | ios::binary);

  if (!outFile) return false;

  // write structure variable B to file
  outFile.write((char*)&B, sizeof(BOOK));

  outFile.close(); // close the file
  return true;
}

void main()
{
  Example5("myfile3.txt");
}

 

6. Example of reading a structural variable from the file

This example is a continuation of the previous example from paragraph 5. In the example, the function Example6() fills the value of a structure variable of type BOOK. The resulting value is formed as an input parameter-reference to the BOOK type. The function also receives the file name for reading as a parameter. To read the structure variable, the read() function is used.

#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;

// reading a BOOK structure from the filename file
// It uses the function read()
bool Example6(const char * filename, BOOK& B)
{
  ifstream inFile(filename, ios::in | ios::binary);
  if (!inFile) return false;

  // get the structure variable B from the file
  inFile.read((char *)&B, sizeof(BOOK));

  inFile.close();
  return true;
}

void main()
{
  BOOK B; // reading from a file and writing to a structural variable B
  Example5("myfile3.txt"); // write to file
  Example6("myfile3.txt", B); // read from file

  // display the contents of variable B
  cout << "B.title = " << B.title << endl;
  cout << "B.author = " << B.author << endl;
  cout << "B.price = " << B.price << endl;
  cout << "B.year = " << B.year << endl;
}

The result of the program

B.title = Title of book
B.author = Authof of book
B.price = 12.65
B.year = 2000

 

7. An example of reading/writing an array of structures to a file. Functions write(), read()

The example uses the write(), read() functions to work with a structure of type BOOK, namely:

  • write an array of type BOOK to a file, which consists of three structural variables;
  • reading an array of structures of type BOOK from a file.

 

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

// The BOOK structure
struct BOOK
{
  char title[100]; // title of the book
  char author[70]; // author
  int year; // year of issue
  float price; // book cost
};

// Writing an array of structures to a file using the write() function
// Reading an array of structures from a file using the read() function
bool Example7(const char * filename)
{
  // demonstrates writing to a file and reading from this file
  // an array of structures of type BOOK
  BOOK B[3] = {
    { "Title-01", "Author-01", 2005, 100.95 },
    { "Title-02", "Author-02", 2008, 90.25 },
    { "Title-03", "Author-03", 2002, 180.50 }
  };
  int n = 3; // the number of elements in array B
  BOOK C[3]; // another array in which the reading will be done
  int n2; // the number of items in the array C
  int i;

  // 1. Writing an array of structures to a file
  // outF - instance of the file to which the record is implemented
  ofstream outF(filename, ios::out | ios::binary);
  if (!outF) return false;

  // write the value of n
  outF.write((char*)&n, sizeof(int));

  // writing array B[] to wf file
  for (i = 0; i < n; i++)
  outF.write((char*)&(B[i]), sizeof(BOOK));
  cout << "Array is written\n" << endl;

  // after you finish working with the file, you need to close it (required)
  outF.close();

  // 2. Reading an array of structures from a file
  // inF - instance of the file to read from
  ifstream inF(filename, ios::in | ios::binary);

  if (!inF) return false;

  cout << "Read the array...\n";

  // Read the number of recorded structures first
  inF.read((char*)&n2, sizeof(int));

  // loop of reading an array of structures into a variable C
  for (i = 0; i < n2; i++)
  inF.read((char*)&(C[i]), sizeof(BOOK));

  inF.close(); // close the file

  // output of array C to the screen
  cout << "Array C:" << endl;
  for (i = 0; i < n2; i++)
  {
    cout << "Title = " << C[i].title << ", ";
    cout << "Author = " << C[i].author << ", ";
    cout << "Year = " << C[i].year << ", ";
    cout << "Price = " << C[i].price << endl;
  }
}

void main()
{
  Example7("file7.bin");
}

The result of the program

Array is written
Read the array...
Array C:
Title = Title-01, Author = Author-01, Year = 2005, Price = 100.95
Title = Title-02, Author = Author-02, Year = 2008, Price = 90.25
Title = Title-03, Author = Author-03, Year = 2002, Price = 180.5

 

8. Example of writing/reading an array of double numbers

Demonstrated:

  • write to the file an array of M numbers of type double with the write() function;
  • reading from the file an array of numbers of type double with the help of read() function.





The file is opened in binary format.

#include <iostream>>
#include <fstream>
using namespace std;

// the use of read(), write() functions to write/read an array of numbers
bool Example8(const char * filename)
{
  // array of numbers
  double M[] = { 2.44, 3.85, -3.23, 11.85, 3.38 };

  int i;
  int n = 5; // the number of items in the array M

  // 1. Writing an array to a file
  // 1.1. Create an outF instance associated with filename
  ofstream outF(filename, ios::out | ios::binary);

  // 1.2. Checking if a file is open
  if (!outF)
  {
    cout << "Error. Cannot open the file.";
    return false;
  }

  // 1.3. Write the number of elements in the array M
  outF.write((char*)&n, sizeof(int));

  // 1.4. Write the entire array to a file
  outF.write((char*)&M, sizeof(double)*n);
  outF.close(); // close the file

  // 2. Reading data from filename to array M2
  double M2[5];
  int n2;

  // 2.1. Open file for reading
  ifstream inF(filename, ios::in | ios::binary);

  // 2.2. Check if a file is open?
  if (!inF)
  {
    cout << "Error. Cannot open file.";
    return false;
  }

  // 2.3. Read the number of items in an array
  inF.read((char*)&n2, sizeof(int));

  // 2.4. Read data from file to array M2
  inF.read((char*)&M2, sizeof(double)*n2);
  inF.close(); // close the file

  // 2.5. Print the array M2 to screen
  cout << "Array M2:\n";
  for (i = 0; i < n2; i++)
    cout << M2[i] << " ";
  cout << endl;

  return true;
}

void main()
{
  Example8("file8.bin");
}

The result of the program:

Array M2:
2.44 3.85 -3.23 11.85 3.38

 

9. An example of reading lines from a file. Function getline()

The Example9() function implements line-by-line reading from a file using the getline() function. The file name is specified as the input parameter filename. Lines in a file consist of a set of words separated by a space character.

#include <iostream>
#include <fstream>

using namespace std;

// Reading from a file. Function getline()
bool Example9(const char* filename)
{
  ifstream inputFile(filename);
  char buffer[255]; // buffer for saving one line

  if (!inputFile)
  {
    cout << "Error. Cannot open file";
    return false;
  }

  // loop reading lines from a file
  while (inputFile)
  {
    inputFile.getline(buffer, 255);
    if (inputFile)
      cout << buffer << endl; // output of the reading line to the screen
  }

  inputFile.close();
  return true;
}

 

10. An example of reading lines from a file. Functions getline() + eof()

The example implements the function Example10(), which reads lines from a file. The file opens in text format. The file name is set by the input parameter of the function. Determining the end of a file is done using the eof() function.

#include <iostream>
#include <fstream>
using namespace std;

// reading from a file. Functions getline()+eof()
bool Example10(const char* filename)
{
  // create instance of file
  ifstream inputFile(filename, ios::in);
  if (!inputFile) return false;

  char buffer[255]; // buffer for saving one string

  // file lines reading cycle
  // lines are read until the end of the file is reached
  while (!inputFile.eof())
  {
    inputFile.getline(buffer, 255);
    if (inputFile)
      cout << buffer << endl;
  }

  inputFile.close();
}

 


Related topics