Random reading and writing of C + + files

Posted by taddis on Sun, 30 Jan 2022 04:50:09 +0100

summary

The operation mode of files is divided into sequential reading and writing and random reading and writing Sequential read / write means that the pointer of the file can only be moved from the beginning to the end Random reading and writing means that the file pointer can be moved freely as needed

Random reading and writing

File pointer: there is a file pointer in disk file operation, which is used to indicate the location of reading and writing

function

File stream provides some member functions about file pointers:

Member functioneffect
gcount()Returns the number of bytes read in the last input
tellg()Returns the current position of the input file pointer
seekg (location in file)Move the pointer in the input file to the specified position
seekg (displacement, reference position)Move to the specified position based on the reference position
tellp()Returns the current position of the output file pointer
seekp (location in file)Moves the pointer in the output file to the specified position
seekp (displacement, reference position)Move several bytes based on the reference position
  • G - used for input function (get), e.g. seekg used for output file
  • p - for output function (put), for example, seekp for output file
  • Others - both input and output files, any two sets of functions

example

Input 10 integers from the keyboard and save them to the data file F1 DAT, read the data from the file and display it on the screen

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

int main() {
    int a[10], b[10];
    
    // Open file
    fstream iofile("temp.txt", ios::in | ios::out);
    if(!iofile) {
        cerr << "open error!" << endl;
        exit(1);
    }
    
    // write file
    cout << "enter 10 integer numbers:\n";
    for (int i = 0; i < 10; ++i) {
        cin >> a[i];
        iofile << a[i] << " ";
    }
    
    // read file
    cout << "The numbers have been writen to file." << endl;
    cout << "Display the data by read from file:" << endl;

    iofile.seekg(0, ios::beg);
    for (int i = 0; i < 10; ++i) {
        iofile >> b[i];
        cout << b[i] << " ";
    }
    iofile.close();

    return 0;
}

Output result:

enter 10 integer numbers:
1 2 3 4 5 6 7 8 9 10
The numbers have been writen to file.
Display the data by read from file:
1 2 3 4 5 6 7 8 9 10

Pointer stream member function

The position and displacement in the file are long, in bytes
The reference position can be one of the following three:

  • IOS:: begin with beg file (default)
  • Current position of ios::cur pointer
  • End of ios::end file


Usage: take seekg (displacement, reference position) as an example:

  • file.seekg(3): the pointer moves to the position of the third character
  • file.seekg(ios_base::beg): the pointer moves to the beginning of the file
  • file.seekg(-3, ios_base::cur): move back three characters
  • file.seekg(3, file.tellg()): move back three characters
  • file.seek(file. tellg() + 3): move back three characters

Random access to binary data

By using member function to move pointer, the data in any position in binary data file can be accessed randomly, and the content in the file can also be modified

Student data processing:

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

int main() {
    // Open file
    fstream iofile("student.txt",ios::in|ios::out);
    if(!iofile) {
        cerr << "open error!" << endl;
        exit(1);
    }

    // Output data of 2 students to disk file
    Student stud[2]{
            {1, "Little White"},
            {2, "Big White"}
    };

    for (int i = 0; i < 2; ++i) {
        iofile.write((char *) &stud[i], sizeof(stud[i]));
    }
    // Read student data and display
    Student read[2];
    for (int i = 0; i < 2; ++i) {
        iofile.seekg(i*sizeof(stud[i]),ios::beg);
        iofile.read((char *)&read[i],sizeof(read[0]));
    }

    // Modify the data of the second student and save it back to the original location of the file
    stud[1].setId(1012); //modify
    stud[1].setName("Wu");
    iofile.seekp(sizeof(stud[0]),ios::beg);
    iofile.write((char *)&stud[1],sizeof(stud[2]));
    iofile.seekg(0,ios::beg);


    // Read in the revised data of the two students and display it
    for(int i=0; i<2; i++)
    {
        iofile.read((char *)&stud[i],sizeof(stud[i]));
        stud[i].display();
    }
    iofile.close( );
    return 0;
}

Output result:

id= 1
name= Little White
id= 1012
name= Wu