Attention Problems in Reading and Writing Files of fstream

Keywords: iOS

Classes ofstream, ifstream and fstream are three classes of file operations, derived from ostream, istream and iostream, respectively. Usually ifstream and OFSTREAM are used to read and write files respectively.

1. Open the file

void open (const char * filename, openmode mode);

filename is a string representing the name of the file to be opened. mode is a combination of the following identifiers:

mode Explain
ios::in Open the file for input (reading)
ios::out Open the file for output (write)
ios::ate Initial location: end of file
ios::app All output is appended at the end of the file
ios::trunc If the file already exists, delete it first
ios::binary Binary mode

The default way to read and write three classes is

class Default read-write mode
ofstream ios::out
ifstream ios::in
fstream ios::in

Note: Default values are only adopted when the function is called without declarative parameters. If any parameter is declared when the function is called, the default value will be completely overwritten without being combined with the calling parameter.

These identifiers can be used in combination at intervals of "or" operators (|). For example, open the file "file1.dat" in binary mode and continue to write something; otherwise

ofstream file;
file.open ("file1.dat", ios::out | ios::app | ios::binary);

2. Text files

You can read and write fstream file streams directly through overloaded operators like std::cout and std::cin.
Eg1 : writing on a text file

#include <fiostream.h>
int main () 
{
    ofstream examplefile ("example.txt");
    if (examplefile.is_open()) {
    examplefile << "This is a line.\n";
    examplefile << "This is another line.\n";
    examplefile.close();
    }
    return 0;
}

*** file example.txt ***
This is a line.
This is another line. 

Eg2 : reading a text file

#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
int main () 
{
    char buffer[256];
    ifstream examplefile ("example.txt");
    if (! examplefile.is_open())
    { 
        cout << "Error opening file"; exit (1); 
    }
    while (! examplefile.eof() ) 
    {
        examplefile.getline (buffer,100);
        cout << buffer << endl;
    }
    return 0;
}

----- Console  -----
This is a line. 
This is another line. 

Text files are relatively simple to read and write, but also contain a large number of functions, specific can see the following website
http://www.cplusplus.com/reference/fstream/fstream/?kw=fstream.

Given an example of reading and writing data, we first save some data to the file "fatures.txt", including a data int num, and then save num vectors < double > featuresVec. Then read the file.

Eg3: Save some data to the file "fatures.txt"

    vector<double> featuresVec;
    /*
     ....   featuresVec Data writing is omitted, assuming 17 values
    */
    ofstream fout("fatures.txt");
    int num = 160;
    fout << num << " ";
    for (int i = 0; i < num; i++) {
        for (double au : featuresVec){   
            fout << au <<" ";  //Write every data for featuresVec
        }
    }
    fout.close();

Eg4: Read the data in the file "fatures.txt"

    ifstream fin("fatures.txt");

    int num;
    fin >> num;

    vector<vector<double>> ausVec;  //Read num vectors < double > Data

    for (int i = 0; i < num; i++)
    {
        vector<double> tempVec;

        for (int j = 0; j < 17; j++) { //Keep the same amount of data as when writing
            double temp;
            fin2 >> temp;  //Read each data in vector < double >
            tempVec.push_back(temp);
        }
        ausVec.push_back(tempVec);
    }
    fin.close();

3. Binary files

Although it is legitimate to use `and', as well as functions (such as getline) to input and output data to operators, these operations have little practical significance in binary files.

The file stream consists of two member functions specially designed for sequential read and write data: write and read. The first function (write) is a member function of ostream, which is inherited by ofstream. Read is a member function of istream, inherited by ifstream. The object of class fstream has both functions. Their prototypes are:

write ( char * buffer, streamsize size );
read ( char * buffer, streamsize size );

Here a buffer is the address of a block of memory used to store or read data. The parameter size is an integer value representing the number of characters to read or write from the buffer.

// reading binary file  
#include <iostream>  
#include <fstream.h>  

const char * filename = "test.txt";  

int main () 
{  
    char * buffer;  
    long size;  
    ifstream in (filename, ios::in|ios::binary|ios::ate);  
    size = in.tellg();  
    in.seekg (0, ios::beg);  
    buffer = new char [size];  
    in.read (buffer, size);  
    in.close();  

    cout << "the complete file is in a buffer";  

    delete[] buffer;  
    return 0;  
}  
//Operation results:  
The complete file is in a buffer  

Note: If you want to read and write binary files, you must specify that the mode of reading and writing is ios::binary, otherwise reading data will be wrong.

Similar to the previous text reading and writing, the corresponding binary reading and writing method is given.
Eg1: Write data to binary file "fatures.dat"

    ofstream fou("fatures.dat", ios::binary);//binary must be specified

    int num = 160;
    fou.write((char*)&num, sizeof(int));  //Write to num

    for (int i = 0; i < num; i++) {

        vector<double> featuresVec; 
        /*  
          ... featuresVec Data writing is omitted, assuming 17 values    
        */
        for (double au : featuresVec){
            //Write each double value of featuresVec,
            fou.write((char*)&au, sizeof(double)); 
        }
    }
    fou.close();

Eg2:, read the data in the binary file "fatures.dat"

    ifstream fin("fatures.dat", ios::binary);  //binary must be specified

    int num;
    fin.read((char*)&num, sizeof(int));  //Read num

    vector<vector<double>> ausVec; //Read num vectors < double > Data

    for (int i = 0; i < num; i++)
    {
        vector<double> tempVec;

        for (int j = 0; j < 17; j++) {//Keep the same amount of data as when writing
            double temp;
            fin.read((char*)&temp, sizeof(double));//Read each data in vector < double >
            tempVec.push_back(temp);
        }
        ausVec.push_back(tempVec);
    }
    fin.close();

Posted by madkris on Fri, 31 May 2019 15:58:06 -0700