Reading random access files [closed]

断了今生、忘了曾经 提交于 2019-12-13 04:13:37

问题


I have developed a C++ application for reading and writing data on a random access file. (I use Visual C++ 2010)

Here is my program:

#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();
}

And output is:

Num: 1
Text: Hello
writing done
Num2: 1
Text2: test
reading done

But i expect Text2: Hello . What is the problem??

By the way , How can I do output.write inside of my class ( in a function) ?

Thanks


回答1:


A is not POD, you can not brutally cast non-POD object to char* then write to stream. You need to serialize A, for example:

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();
} 

This sample serializes object myA to file, you can think about how to read it out.



来源:https://stackoverflow.com/questions/14393774/reading-random-access-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!