Чтение файлов с произвольным доступом

Я разработал приложение 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 внутри моего класса (в функции)?

Спасибо

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 в файл, вы можете подумать о том, как его прочитать.

Другие вопросы по тегам