顺序读取从二进制文件结构中的C ++ [英] sequentially reading a structs from binary file in C++

查看:159
本文介绍了顺序读取从二进制文件结构中的C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个程序,该程序执行操作时,
(实施例:搜索,更新,或添加),它应该是直接访问。该程序
不应该读所有的记录顺序将达到创纪录。

I'm trying to write a program, when the program is performing an operation (Example: search, update, or add), it should be direct access. The program should not read all the records sequentially to reach a record.

 #include <iostream>
#include <fstream>
#include <string>

using namespace std;

struct Student{
    int Id;
    int Money;
    int Age;
    char name[15];
};

void main(){
    Student buffer;
    ofstream BinaryFile("student", ios::binary);
    ifstream WorkerText("worker.txt");

//-------------------------------------------------------------------------------------------------------------
    while( WorkerText.good() ){                     
        WorkerText>> buffer.Age >> buffer.name >> buffer.name >> buffer.name;
        BinaryFile.write(  (char *) &buffer, sizeof(Student)  );    

    }
    BinaryFile.close();
//-------------------------------------------------------------------------------------------------------------
    ifstream ReadBinary( "student", ios::binary | ios::out );
    while( BinaryFile.good() ){                     
        ReadBinary.read((char*)&buffer,sizeof(Student));
        cout<<buffer.Age;

    }


//-------------------------------------------------------------------------------------------------------------


system("pause");
}

我stucked在这里我不能按顺序读取我怎么能解决这个问题。

I stucked here I could not read sequentially how can I solve this

推荐答案

如果该文件包含相同尺寸的结构,或使用一些索引表。可以跳过顺序只读

You can skip sequential read only if the file contains structures of the same size, or uses some index table.

有关大小相同的结构的情况下:

For the case of structures of same size:

void ReadStudent(istream &src, Student &dst)
{
    src.read(&dst, sizeof(dst));
}

void GoToStudentIndex(istream &src, size_t idx)
{
   src.seekg(idx * sizeof(Student), is.beg);
 }

上面的函数假设你正在写数据如下:

The functions above assume you are writing data as follows:

void WriteStudent(ostream &dst, const Student &src)
{
    dst.write(&src, sizeof(src));
}

这篇关于顺序读取从二进制文件结构中的C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆