2013-01-18 83 views
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

感谢

+5

您不能读写非字节流中的非POD结构。你的'A'包含一个不是POD的'std :: string',因此'A'不是POD。另外,读取可能会失败。 –

+0

我忘了在这里写下我的preprosecor命令......编辑的问题。 – Arashdn

+0

@Seth Carnegie,我能做些什么来在文件中写字符串? – Arashdn

回答

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

此示例对象序列化到妙文件,你可以想想如何读出来。

+0

即使是大多数POD也存在问题。你通常必须定义一个格式,然后编写它。 (有一个原因,为什么'istream :: read'和'ostream :: write'采用'char *',而不是'void *'。) –

+0

感谢您的回复 - 但我无法理解您如何包含写入函数里面的课... – Arashdn

+0

@Arashdn哪一个你不明白? – billz