【问题标题】:Reading random access files [closed]读取随机访问文件[关闭]
【发布时间】: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


【解决方案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序列化为文件,大家可以想想怎么读出来。

【讨论】:

  • 即使是大多数 POD 也存在问题。您通常必须定义一种格式并编写它。 (istream::readostream::write 采用 char* 而不是 void* 是有原因的。)
  • 感谢您的回复 - 但我不明白您是如何在课堂内包含写作功能的......
  • @Arashdn 哪一个你不明白?
  • @billz 第二个,我删除了 unicode,我使用 ofstream 和 char * 作为数据类型,我还删除了字符串,现在我只有 2 个 int 值。在课堂上移动我的写作功能的最简单方法是什么???
  • 您只需将wofstream 替换为ofstream,将wstring 替换为string,然后我的示例代码就可以工作了。
猜你喜欢
  • 1970-01-01
  • 2018-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多