c++ - C++ 文件读写

标签 c++ fstream ifstream ofstream

我正在尝试在 C++ 中读取对象并将其写入文件,写入对象工作正常,读取提供分段核心转储。我已经注释了写入对象到文件的代码,在编写时我们可以取消注释这部分并注释读取部分。

#include<iostream>
#include<fstream>
#include<string>

using namespace std;

class RelianceMart{
    string name;
    double trolley_number;
public:
    RelianceMart(){
        name = "NA";
        trolley_number = 0;
    }
    RelianceMart(string name, double trolley_number){
        this->name = name;
        this->trolley_number = trolley_number;
    }
    void setname(string name){
        this->name = name;
    }
    string getname(){
        return name;
    }
    void settrolleynumber(double trolley_number){
        this->trolley_number = trolley_number;
    }
    double gettrolleynumber(){
        return trolley_number;
    }
};

int main(){
    string name;
    double trl_num; 
    RelianceMart mart[3];
    RelianceMart obj;
//  ofstream fout("PersistentStorage.txt");
/*
    for(int i=0;i<3;i++){
        cin>>name;
        cin>>trl_num;
        mart[i] = RelianceMart(name, trl_num);
        fout.write((char *) & mart[i], sizeof(mart[i])); 
    }

    fout.close();
*/
    ifstream fin("PersistentStorage.txt");

    while(!fin.eof()){
        fin.read((char *) & obj,sizeof(obj));
        cout<< obj.getname();
    }
    fin.close();

    return 0;
}

最佳答案

std::string的成员实际上只不过是长度的成员变量,而成员变量是指向实际字符串内容的指针

在所有现代 protected 多任务操作系统中,指针对于特定进程都是私有(private)的和唯一的,没有其他进程(即使是从同一程序启动的进程)也不能重复使用相同的指针。

当你写 RelianceMart对象,你写下 name 的指针字符串对象到文件。如上所述,没有其他进程可以使用此指针,因此无法读取该文件。

此外当您尝试读取原始对象时,您读取的原始数据会覆盖已构造对象中的现有数据,并且该对象将无法再正确构造.

您也没有以二进制模式打开文件,这是错误的,因为您写入和读取的是原始二进制数据,而不是文本。


常见的解决方案是使用 serialization ,最常见的方法是简单地重载“输出”和“输入”运算符 <<>> .

在重载函数中,您只需将每个对象作为文本写入和读取,再次使用格式化的 <<>>运营商。


最后请阅读Why is iostream::eof inside a loop condition considered wrong?

关于c++ - C++ 文件读写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51232818/

相关文章:

c# - 在 C# 中使用 native C++ 代码 - std::vector 的问题

c++ - 如何在Qt中制作exe文件?

c++ - ifstream 和 ofstream 或 fstream 使用 in 和 out

c++ - 具有挑战性的数据文件格式,需要读入包含类对象的数组变量

c++ - 从 .txt 文件中读取一行并插入到变量中

c++ - 我可以将 ifstream 重定向到 cin 吗?

c++ - 具有 ifstream 成员的内部类的构造函数返回无效的 fstream

c++ - 如何从 gcc 内联 arm7 程序集调用 c++ 成员函数

c++ - Type Traits - 显式模板特化。在 xcode 上失败

C++如何使用fstream读取带空格的制表符分隔文件