【问题标题】:Why I fail to read object from a file?为什么我无法从文件中读取对象?
【发布时间】:2020-08-11 06:56:42
【问题描述】:

我想将字符串对象输出到文件并将其取回,但我的代码根本不打印任何内容。

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

void main()
{
    // open file for binary input/output
    fstream binary("data.txt", ios::binary);

    // create random string
    string str1 = "fgh";

    // write down string object to the file
    binary.write(reinterpret_cast<char*>(&str1), sizeof(str1));

    // create second string
    string str2;

    // get str1 to str2
    binary.read(reinterpret_cast<char*>(&str2), sizeof(str1));

    // print second string
    cout << str2;
}

【问题讨论】:

  • 您不能以这种方式读取或写入 std::string。它必须是 POD 类型。 std::string 是一个带有指针的类。当您以这种方式读写时,您保存的是指针而不是指针指向的数据。
  • 非常小心reinterpret_cast。通常你不需要它。当你认为你需要它(或它的 C 风格转换等价物)时,你通常会写一个错误。 极少种情况reinterpret_cast实际上是正确的解决方案。
  • 查找对象序列化/反序列化。

标签: c++ object binaryfiles fileoutputstream


【解决方案1】:

我认为下面写的代码是不言自明的。

您不需要(也不应该使用)二进制文件来存储std::string。将它们存储在由分隔符分隔的文本文件中。

#include <fstream>
#include <iostream>
#include <string>
using namespace std;

int main() { // void main doesn't work on C++

    // open file for binary input/output
    fstream file("data.txt", ios::in | ios::out); // .txt file is not a binary file dude

    // check if file already exists or not
    // file will not be automatically created because ios::in mode is also being used
    if (not file) {
        cerr << "No such file present!" << endl;
        return -1;
    }

    // create random string
    string str1 = "fgh";

    // write down string object to the file
    // binary.write(reinterpret_cast<char*>(&str1), sizeof(str1));
    file << str1 << endl; // if you are removing std::endl from here then add std::flush

    // set get pointer at beginning because write operation has moved it to end
    // it is always better to use two file objects (one ifstream and one ofstream) for such projects.
    file.seekg(ios::beg);

    // create second string
    string str2;

    // get str1 to str2
    // binary.read(reinterpret_cast<char*>(&str2), sizeof(str1));
    file >> str2;

    // print second string
    cout << str2;

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-02
    • 1970-01-01
    相关资源
    最近更新 更多