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

目录

  • 概述
  • 随机读写
  • 函数
  • 例子
  • 指针流成员函数
  • 随机访问二进制数据

概述 【C/C++中文件的随机读写详解及其作用介绍】文件的操作方式分为顺序读写和随机读写. 顺序读写指文件的指针只能从头移到尾巴. 随机读写指文件指针可以随意移动, 根据需要.
C/C++中文件的随机读写详解及其作用介绍
文章图片


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

函数 文件流提供了一些有关文件指针的成员函数:
成员函数 作用
gcount() 返回最后一次输入所读入的字节数
tellg() 返回输入文件指针的当前位置
seekg (文件中的位置) 将输入文件中指针移到指定的位置
seekg (位移量, 参照位置) 参照位置为基础移动到指定的位置
tellp() 返回输出文件指针当前的位置
seekp (文件中的位置) 将输出文件中指针移到指定的位置
seekp (位移量, 参照位置) 以参照位置为基础移动若干字节
  • g- 用于输入函数 (get), 例如 seekg 用于输出文件
  • p- 用于输出函数 (put), 例如 seekp 用于输出文件
  • 其他- 既可以输入又可输出的文件, 任意使者两组函数.

例子 从键盘输入 10 个整数, 并将其保存到数据文件 f1. dat 中, 再从文件中将数据读出来, 显示在屏幕上.
#include #include 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型, 以字节为单位.
参照位置可以是下面三者之一:
  • ios::beg 文件开头 (默认)
  • ios::cur 指针当前的位置
  • ios::end 文件末尾
C/C++中文件的随机读写详解及其作用介绍
文章图片

用法: 以 seekg (位移量, 参照位置) 为例:
  • file.seekg(3): 指针移动到第三个字符的位置
  • file.seekg(ios_base::beg): 指针移动到文件开头
  • file.seekg(-3, ios_base::cur): 向后移动三个字符
  • file.seekg(3, file.tellg()): 向后移动三个字符
  • file.seek(file. tellg() + 3): 向后移动三个字符

随机访问二进制数据 利用成员函数移动指针, 随机地访问二进制数据文件中任意一位置上的数据, 还可以修改文件中的内容.
学生数据处理:
#include #include #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++随机读写内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

    推荐阅读