观察在文件读操作过程中位置指针的变化(P321)
/*
背景:
如果一个文件只能进行顺序存取操作,则称为顺序文件。典型的顺序文件是键盘、显示器和保存在磁带上的文件。
如果一个文件可以在文件的任意位置进行存取操作,则称为随机文件。磁盘文件就是典型的随机文件。
类istream中与位置指针相关的函数如下:
(1)移动读指针函数:
a、istream & seekg(long pos);
功能是将读指针设置为pos,即将读指针移动到文件的pos字节处。
b、istream & seekg(long offset,ios::seek_dir dir);
功能是将读指针按照seek_dir的指示(方式)移动offset个字节,其中seek_dir是在类ios中定义的一个枚举类型。
(2)返回读指针当前位置值的函数
long tellg();
函数返回值为流中读指针的当前位置。
*/
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
class CStudent
{
public:
char id[11]; //学号
char name[21]; //姓名
int score; //成绩
};
int main()
{
CStudent stu;
int count =0,nbyte =0;
ifstream inFile("students.dat",ios::in|ios::binary); //以二进制读方式打开
if (!inFile) //条件成立,则说明文件打开出错
{
cout<<"创建文件失败"<<endl;
return 0;
}
else
{
cout<<"打开文件时位置指针:"<<inFile.tellg()<<endl;
cout <<"每个记录大小:"<<sizeof(CStudent)<<endl;
}
cout<<"学生学号 姓名\t\t\t 成绩\t 流指针\n";
while (inFile.read((char*)&stu,sizeof(CStudent))) // 读取一个记录
{
cout<<left<<setw(10)<<stu.id<<" "<<setw(20)<<stu.name
<<" "<<setw(3)<<right<<stu.score<<"\t"<<inFile.tellg()<<endl;
count ++;
nbyte += inFile.gcount();
}
cout<<"读取文件结束时位置指针:"<<inFile.tellg()<<endl;
cout<<"共有记录数:"<<count<<",字节数:"<<nbyte<<endl;
inFile.clear(); //将流恢复为正常状态。必不可少
inFile.seekg(0); //将文件读指针移动到文件起始位置
cout<<"位置指针:"<<inFile.tellg()<<endl;
inFile.read((char*)&stu,sizeof(stu));
cout<<left<<setw(10)<<stu.id<<" "<<setw(20)<<stu.name
<<" "<<setw(3)<<right<<stu.score<<endl;
inFile.seekg(0,ios::end); //将文件读取指针移动到文件最后位置
cout<<"位置指针:"<<inFile.tellg()<<endl;
inFile.close();
return 0;
}

浙公网安备 33010602011771号