将结构写入二进制文件C ++时遇到麻烦

问题描述 投票:0回答:1

我正在尝试编写一个带有结构的代码,询问用户信息,并将数据放入一个称为“输出”的二进制文件中,以便可以读取它。我尝试用我的代码执行此操作,但是它不起作用。有人可以帮我修复它,并告诉我我做错了什么吗?这是我正在处理的代码。

#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <string>
#include <iomanip>
#include <stdio.h>  
#include <string.h> 
using namespace std;

const int NAME_SIZE = 20;

struct Student{
    char fname[NAME_SIZE]; 
    int id; 

    };

int main() {
    int choice;
    fstream file; 
    Student person;

cout << "Populate the records of the file." << endl;
        file.open("output", ios::out | ios::binary);
        cout << "Populating the record with information."<< endl;      
        cout << "Enter the following data about a person " << endl;
        cout << "First Name: "<< endl;
        cin.getline(person.fname, NAME_SIZE);
        cout << "ID Number: "<< endl;
        cin >> person.id;
        file.write(reinterpret_cast<char *>(&person), sizeof(person));
        file.close();       
return 0;
}

我将非常感谢您的帮助

c++ binaryfiles randomaccessfile random-access
1个回答
0
投票

您正在混合原始二进制数据和字符串数据。如果名称短于NAME_SIZE,则您正在写入文件名,该文件名后面可能包含不可打印的字符。另外int id被写为不可打印的整数。

如果您要存储和加载二进制数据(如二进制协议),则此存储有效。

如果要将数据存储为可读文本,则必须先序列化数据,但无法使用简单的read加载它们>

© www.soinside.com 2019 - 2024. All rights reserved.