[英]Having trouble writing a structure to a binary file C++
我正在嘗試制作一個采用結構的代碼,詢問用戶信息並將數據放入一個名為“輸出”的二進制文件中,以便可以讀取它。 我嘗試用我的代碼來做,但它不起作用。 任何人都可以幫我解決它並告訴我我做錯了什么嗎? 這是我正在處理的代碼。
#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;
}
我真的很感激任何幫助
您正在混合原始二進制數據和字符串數據。 如果名稱比NAME_SIZE
短,您正在編寫的文件名可能在名稱后有不可打印的字符。 int id
也寫為不可打印的 integer。
如果您要存儲和加載二進制數據(如二進制協議),則此存儲是有效的。
如果要將數據存儲為可讀文本,則必須先序列化數據,但無法通過簡單read
來加載它們
正確的方法是為 Student 定義一個 operator<< 和 operator>>。 然后處理保存和讀取結構是小菜一碟。
std::ostream & operator<<(std::ostream & os, Student const & rhs)
{
for(int i=0; i<NAME_SIZE; ++i)
{
os << rhs.fname[i];
}
os << id;
return os;
}
std::istream & operator>>(std::istream & is, Student & rhs)
{
for(int i=0; i<NAME_SIZE; ++i)
{
is >> rhs.fname[i];
}
is >> id;
return is;
}
因此,當您需要保存到文件時,您只需執行以下操作:
file << person;
當您需要從中讀取時:
file >> person;
PS:我建議使運算符實現比這更健壯,也許通過特殊標記,以便您可以在讀取文件時檢測問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.