当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - Writing and reading from a binary file

问题描述:

I'm trying to learn how to write to a binary file and then read the info back into variables. I'm trying to make the info in c3 & c4 the same as c1 & c2 by having it read from the binary file. I've searched and tried for many hours, but I can't figure out what else I'm doing wrong. Please help.

#include <cstring>

#include <iostream>

#include <fstream>

using namespace std;

struct Cat {

char name[50];

int age;

};

//----- TEXT I/O -----//

void display(Cat& cat) {

cout << cat.name << endl;

cout << cat.age << endl;

}

//----- BINARY I/O -----//

void writeBinaryData(ofstream& binaryFile, Cat& cat) {

binaryFile.write(cat.name, sizeof(char[50]));

binaryFile.write(reinterpret_cast<char*>(&cat.age), sizeof(int));

}

void readBinaryData(ifstream& binaryFile, Cat& cat) {

binaryFile.read(cat.name, sizeof(char[50]));

binaryFile.read(reinterpret_cast<char *>(&cat.age), sizeof(int));

}

int main() {

Cat c1, c2, c3, c4;

// c1's name is Ben and age is 2

strcpy(c1.name, "Ben");

c1.age = 2;

// c2's name is Willard and age is 3

strcpy(c2.name, "Willard");

c2.age = 3;

// display c1 & c2

display(c1);

display(c2);

// read and write c1 & c2 to binary data file

ofstream binOut("catfarm.bin", ios::out | ios::binary);

writeBinaryData(binOut, c1);

writeBinaryData(binOut, c2);

// read from binary file into c3 & c4

ifstream binIn("catfarm.bin", ios::in | ios::binary);

readBinaryData(binIn, c3);

readBinaryData(binIn, c4);

display(c3);

display(c4);

return 0;

}

Right now the output looks like this:

Ben

2

Willard

3

32701

32701

But it should look like this:

Ben

2

Willard

3

Ben

2

Willard

3

分享给朋友:
您可能感兴趣的文章:
随机阅读: