如何用C++编写一个对象文件

neu*_*cer 12 c++ string file object

我有一个带有几个文本字符串作为成员的对象.我想一次性将这个对象写入文件,而不是将每个字符串写入文件.我怎样才能做到这一点?

ste*_*anB 10

您可以覆盖operator>>operator<<读/写流.

Entry struct带有一些值的示例:

struct Entry2
{
    string original;
    string currency;

    Entry2() {}
    Entry2(string& in);
    Entry2(string& original, string& currency)
        : original(original), currency(currency)
    {}
};


istream& operator>>(istream& is, Entry2& en);
ostream& operator<<(ostream& os, const Entry2& en);
Run Code Online (Sandbox Code Playgroud)

执行:

using namespace std;

istream& operator>>(istream& is, Entry2& en)
{
    is >> en.original;
    is >> en.currency;
    return is;
}

ostream& operator<<(ostream& os, const Entry2& en)
{
    os << en.original << " " << en.currency;
    return os;
}
Run Code Online (Sandbox Code Playgroud)

然后打开文件流,并为您调用的每个对象:

ifstream in(filename.c_str());
Entry2 e;
in >> e;
//if you want to use read: 
//in.read(reinterpret_cast<const char*>(&e),sizeof(e));
in.close();
Run Code Online (Sandbox Code Playgroud)

或输出:

Entry2 e;
// set values in e
ofstream out(filename.c_str());
out << e;
out.close();
Run Code Online (Sandbox Code Playgroud)

或者,如果您想使用流read,write那么您只需替换operator实现中的相关代码.

当变量在struct/class中是私有的时,你需要将operators 声明为友元方法.

您可以实现任何您喜欢的格式/分隔符.当你的字符串包含空格时,使用getline()接受字符串和流而不是>>因为operator>>默认情况下使用空格作为分隔符.取决于你的分隔符.


Chr*_*s H 6

它被称为序列化.SO上有许多序列化线程.

boost中还包含一个很好的序列化库.

http://www.boost.org/doc/libs/1_42_0/libs/serialization/doc/index.html

基本上你可以做到

myFile<<myObject 
Run Code Online (Sandbox Code Playgroud)

myFile>>myObject
Run Code Online (Sandbox Code Playgroud)

与boost序列化.


use*_*666 5

如果你有:

struct A {
    char a[30], b[25], c[15];
    int x;
}
Run Code Online (Sandbox Code Playgroud)

那么您可以只使用write(fh,ptr,sizeof(struct a))来编写所有内容。

当然,这不是可移植的(因为我们没有保存“ int”的长度或大小,但这对您来说可能不是问题。

如果你有:

struct A {
    char *a, *b, *c;
    int d;
}
Run Code Online (Sandbox Code Playgroud)

那么您就不打算写对象了;您正在寻找序列化它。最好的选择是查看Boost库并使用其序列化例程,因为在没有反思的语言中这不是一个容易的问题。