c++ - 从 C++ 中的二进制文件顺序读取结构

标签 c++ file-io struct binary

我正在尝试编写一个程序,当程序正在执行一个操作时 (例如:搜索、更新或添加),应该是直接访问。该程序 不应顺序读取所有记录以达到记录。

 #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");
}

我卡在这里我无法按顺序阅读我该如何解决这个问题

最佳答案

如果文件包含相同大小的结构,或者使用一些索引表,则可以跳过顺序读取。

对于相同大小的结构的情况:

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);
 }

上述函数假定您正在按如下方式写入数据:

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

关于c++ - 从 C++ 中的二进制文件顺序读取结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15452311/

相关文章:

c++ - 为什么在析构函数中抛出异常时不调用重载删除?

c++ - 删除 .. 在 boost filesystem::complete

linux - Linux 中的无缓冲 I/O

c - C 中结构体定义的变体

xml - 将结构作为参数传递给函数,并返回相应结构的 slice

c++ - 使用带有 ldap_sasl_bind_s 函数的 kerberos 凭证通过 GSSAPI 进行 SASL 绑定(bind)

c++ - 在两个不同的 OpenCV 窗口中显示相同的鼠标光标

c++ - 堆上非常大的数组 (Visual C++)

java - 如何将混合类型文件中的整数存储到数组中? java

c - 在 C99 中强制结构体中枚举值的宽度