• 自考新教材-p321


    源程序:

    #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("c:\tmp\students.dat", ios::in | ios::binary); //以二进制读方式打开
    if (!inFile) //条件成立,则说明文件打开出错
    {
    cout << "创建文件失败" << endl;
    return 0;
    }
    else
    {
    cout << "打开文件时位置指针:" << inFile.tellg() << endl;
    cout << "每个记录大小:" << sizeof(CStudent) << endl;
    }
    cout << "学生学号 姓名 成绩 流指针 ";
    while (inFile.read((char*)&stu, sizeof(CStudent))) // 读取一个记录
    {
    cout << left << setw(10) << stu.id << " " << setw(20) << stu.name
    << " " << setw(3) << right << stu.score << " " << 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();
    system("pause");
    return 0;
    }

    运行结果:

  • 相关阅读:
    textarea聚焦的多种写法
    vue.js入门
    全选,反选
    jquery列表,点击反应
    SqlServer中offset..fetch 的使用问题
    复习Spring第四课---Spring对国际化的支持
    SqlServer的order by问题
    设计模式之---代理模式
    解决SpringMVC重复提交的问题
    Java知识复习(三)
  • 原文地址:https://www.cnblogs.com/duanqibo/p/12263715.html
Copyright © 2020-2023  润新知