【发布时间】:2013-01-01 20:37:35
【问题描述】:
我开发了一个 C++ 应用程序,用于在随机访问文件上读取和写入数据。 (我使用 Visual C++ 2010)
这是我的程序:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class A
{
public :
int a;
string b;
A(int num , string text)
{
a = num;
b = text;
}
};
int main()
{
A myA(1,"Hello");
A myA2(2,"test");
cout << "Num: " << myA.a<<endl<<"Text: "<<myA.b<<endl;
wofstream output; //I used wfstream , becuase I need to wite a unicode file
output.open("12542.dat" , ios::binary );
if(! output.fail())
{
output.write( (wchar_t *) &myA , sizeof(myA));
cout << "writing done\n";
output.close();
}
else
{
cout << "writing failed\n";
}
wifstream input;
input.open("12542.dat" , ios::binary );
if(! input.fail())
{
input.read( (wchar_t *) &myA2 , sizeof(myA2));
cout << "Num2: " << myA2.a<<endl<<"Text2: "<<myA2.b<<endl;
cout << "reading done\n";
}
else
{
cout << "reading failed\n";
}
cin.get();
}
输出是:
Num: 1
Text: Hello
writing done
Num2: 1
Text2: test
reading done
但我希望 Text2: Hello 。
有什么问题??
顺便说一句,我怎样才能在我的班级内(在一个函数中)做output.write?
谢谢
【问题讨论】:
-
你不能像这样在字节流中读写非 POD 结构。您的
A包含一个不是 POD 的std::string,因此A不是 POD。此外,读取可能会失败。 -
我忘记在这里写我的 preprosecor 命令...,问题已编辑。
-
@Seth Carnegie ,我该怎么做才能在文件中写入字符串?
-
@Arashdn 定义二进制格式,并写入。或者使用现有的二进制格式,例如 XDR。
标签: c++ visual-c++ file-io wofstream wifstream