首页 > 编程技术 > C语言

C/C++中文件的随机读写详解及其作用介绍

发布时间:2021-9-3 00:00

概述

文件的操作方式分为顺序读写和随机读写. 顺序读写指文件的指针只能从头移到尾巴. 随机读写指文件指针可以随意移动, 根据需要.

在这里插入图片描述

随机读写

文件指针: 在磁盘文件操作中有一个文件指针, 用来指明进行读写的位置.

函数

文件流提供了一些有关文件指针的成员函数:

成员函数 作用
gcount() 返回最后一次输入所读入的字节数
tellg() 返回输入文件指针的当前位置
seekg (文件中的位置) 将输入文件中指针移到指定的位置
seekg (位移量, 参照位置) 参照位置为基础移动到指定的位置
tellp() 返回输出文件指针当前的位置
seekp (文件中的位置) 将输出文件中指针移到指定的位置
seekp (位移量, 参照位置) 以参照位置为基础移动若干字节

例子

从键盘输入 10 个整数, 并将其保存到数据文件 f1. dat 中, 再从文件中将数据读出来, 显示在屏幕上.

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

int main() {
    int a[10], b[10];
    
    // 打开文件
    fstream iofile("temp.txt", ios::in | ios::out);
    if(!iofile) {
        cerr << "open error!" << endl;
        exit(1);
    }
    
    // 写入文件
    cout << "enter 10 integer numbers:\n";
    for (int i = 0; i < 10; ++i) {
        cin >> a[i];
        iofile << a[i] << " ";
    }
    
    // 读取文件
    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;
}

输出结果:

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

指针流成员函数

文件中的位置和位移量为long型, 以字节为单位.
参照位置可以是下面三者之一:

在这里插入图片描述

用法: 以 seekg (位移量, 参照位置) 为例:

随机访问二进制数据

利用成员函数移动指针, 随机地访问二进制数据文件中任意一位置上的数据, 还可以修改文件中的内容.

学生数据处理:

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

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

    // 向磁盘文件输出2个学生的数据
    Student stud[2]{
            {1, "Little White"},
            {2, "Big White"}
    };

    for (int i = 0; i < 2; ++i) {
        iofile.write((char *) &stud[i], sizeof(stud[i]));
    }
    // 读取学生数据,并显示
    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]));
    }

    // 修改第2个学生的数据后存回文件原位置
    stud[1].setId(1012); //修改
    stud[1].setName("Wu");
    iofile.seekp(sizeof(stud[0]),ios::beg);
    iofile.write((char *)&stud[1],sizeof(stud[2]));
    iofile.seekg(0,ios::beg);


    // 读入修改后的2个学生的数据并显示出来
    for(int i=0; i<2; i++)
    {
        iofile.read((char *)&stud[i],sizeof(stud[i]));
        stud[i].display();
    }
    iofile.close( );
    return 0;
}

输出结果:

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

到此这篇关于C/C++中文件的随机读写详解及其作用介绍的文章就介绍到这了,更多相关C++随机读写内容请搜索猪先飞以前的文章或继续浏览下面的相关文章希望大家以后多多支持猪先飞!

标签:[!--infotagslink--]

您可能感兴趣的文章: