C++: Read and write classes
C++: Read and write classes
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class PERSON{
string name, surname;
public:
void set_name(string aname, string asurname){
name = aname;
surname = asurname;
};
void read(){
}
void output(){
cout << name << " " << surname << "n";
}
void save(PERSON *x){
ofstream file("test.bin", ios::out | ios::app | ios::binary);
if(!file.is_open()){
cout << "ERRORn";
}else{
file.write((char*)x, sizeof(*x));
file.close();
}
}
};
/*
*
*
*
*/
int main(int argc, char** argv) {
PERSON * person1 = new PERSON;
PERSON * person2 = new PERSON;
person1->set_name("Amon", "Raa");
person1->save(oseba1);
ifstream file2("test.bin", ios::in | ios::binary);
if(!file2.is_open()){
cout << "Errorn";
return 0;
}
while(!file2.eof()){
file2.read((char *)person2, sizeof(*person2));
person2->output();
}
file2.close();
return 0;
}
这是我的代码…我做错了什么?我想做的是每次保存一个类到二进制文件的末尾,然后读取所有条目…
但是每次我运行程序时,我只输出最后输入的名称
所以第一次运行它文件写入正确,输出正常然后我把名字改成别的东西,比如John Doe,我得到的输出是2乘以John Doe
请帮…我完全是初学者;(
例如,类的序列化包含在boost包中。
http://www.boost.org/doc/libs/1_53_0/libs/serialization/doc/index.html我不认为你真的想自己实现这些功能。
在c++中不能简单地写出类的二进制映像,特别是包含指针和非pod成员的类。一旦你在你的数据中有了间接,简单地写出一个内存映像是行不通的,因为仅仅写出类的内存映像不包括指向数据,而且为了让它工作,你必须把所有的数据,包括指向数据,加载到你保存它们时所在的内存位置。这可不容易(委婉点说)。
你有两个选择,一个是手动的,一个是使用第三方库:
1)你用一堆记帐信息分别写和读每个成员。这在你的情况下应该是可行的因为你真正需要加载和保存的只是两个字符串的内容和它们各自的长度
必须使用PERSON类的指针数组。然后从二进制文件中读取并填充人员数组。
ifstream input("PERSON.std",ios::binary);
input.seekg(0, ios::end);
int count = input.tellg() / sizeof(PERSON);
PERSON *persons = new PERSON[count];
input.seekg(0, ios::beg);
input.read((char*) persons, sizeof(PERSON)*count);
cout << count << endl;
for (int j = 0; j < count; j++)
{
cout << count << endl;
cout <<persons[j].output() << "n";
}
cout << 'n';
input.close();
相关文章:
- 尝试链接我的着色器时,我收到错误代码"error c5145 must write to gl_position"
- 当客户端在 write() 期间终止连接时,由对等套接字错误重置连接
- Qt 写入 xml: QIODevice::write (QFile, "D:/logs.xml" ): 设备未打开
- write() 和 read() 中几乎没有混淆
- OpenCV-contrib/Python/Windows:Tracker.write() 在 matrix_wrap.
- Threads with Classes and std::packaged_task
- asio::read() 需要很长时间,使用 asio::write 没有问题
- 封送指向结构异常"cannot Read or Write protected memory"的指针数组的指针数组
- BLE gattServer.write()重载函数
- C++ write(); 反向写入给定的字节值
- 使用 QFile::write 的正确方法?
- C++ UDP 广播使用 ::write
- 是否可以从从 QPrintPreviewDialog 调用的 QPrinter 对话框中删除"Write to PDF"?
- 为什么 fstream.read 和 fstream.write 使用 char 而不是无符号字符?
- 使用 insertion(<<) 运算符和 "write" 函数在 C++ 中显示数据有什么区别?
- C++ Classes/Confusion
- 在使用Qt Designer Form Classes扩展我自己的自定义小部件时防止重复的自动连接
- 一次读取一个字符的文件,直到使用 read(2) 和 write(2) 换行符
- char* 如何读取十六进制的这个整数?它在 ostream::write() 中是如何工作的
- C++: Read and write classes