c++ - 如何在 C++ 中将对象写入文件

标签 c++ file object string

我有一个包含多个文本字符串作为成员的对象。我想一次将此对象全部写入文件,而不是将每个字符串写入文件。我该怎么做?

最佳答案

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

示例 Entry struct有一些值(value):

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

实现:

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

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

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

或输出:

Entry2 e;
// set values in e
ofstream out(filename.c_str());
out << e;
out.close();

或者如果你想使用流 readwrite那么你只需替换 operator 中的相关代码s 实现。

当变量在你的结构/类中是私有(private)的,那么你需要声明 operator s 作为友元方法。

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

关于c++ - 如何在 C++ 中将对象写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2376193/

相关文章:

c++ - 从 C++ 函数返回灵活的数据类型

c++ - 构建错误 : "cannot find target for file" and "undefined reference"

c++ - 使用 biicode 指定替代源文件目录

php - 整个网页使用一个文件的优点和缺点?

c - 在 C 中反序列化文本文件数据(链表)

linux - 执行附加在可执行文件末尾的机器代码

javascript - 根据数组项对象属性值查找数组的索引值

c++ - 如何阻止 VS2K10 缓存环境变量

file - Antcall:从另一个文件调用嵌套的 Ant 目标

javascript - 使用 javascript 控制 .mov (<object>) 文件?