0

我开发了一个 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在我的班级内(在一个函数中)?

谢谢

4

1 回答 1

1

A 不是 POD,你不能粗暴地将非 POD 对象转换为char*然后写入流。您需要序列化A,例如:

class A
{
public :
    int a;
    wstring b;
    A(int num , wstring text)
    {
        a = num;
        b = text;
    }
};

std::wofstream& operator<<(std::wofstream& os, const A& a)
{
  os << a.a << " " << a.b;
  return os;
}

int main()
{
    A myA(1, L"Hello");
    A myA2(2, L"test");

    std::wcout << L"Num: " << myA.a<<endl<<L"Text: "<<myA.b<<endl;

    wofstream output; //I used wfstream , becuase I need to wite a unicode file
    output.open(L"c:\\temp\\12542.dat" , ios::binary );
    if(! output.fail())
    {
      output << myA;
      wcout << L"writing done\n";
      output.close();
    }
    else
    {
        wcout << "writing failed\n";
    }

    cin.get();
} 

此示例将对象 myA 序列化为文件,您可以考虑如何将其读取出来。

于 2013-01-18T07:09:36.987 回答