在struct to file中使用字符串而不是char数组和read()以及write()

时间:2016-12-07 19:19:53

标签: c++

是否可以使用string代替char[]中的struct数组,并使用read和{{{{}}}保存到文件中1}}函数没有出现运行时错误?

write

1 个答案:

答案 0 :(得分:1)

std::string(或任何其他动态大小的容器)包含指向其字符数据的指针,该指针存储在内存中的其他位置。如果你原来read() / write() std::string本身,你只会读/写指针值,而不是实际的字符数据。固定阵列不是这种情况。

要在std::string中使用struct,您必须(de)序列化来回struct的内容,以便您可以考虑动态数据。

例如:

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

using namespace std;

struct details
{
    string name;
    int32_t add_year;
};

istream& operator>>(istream &in, details &out)
{
    int32_t len;
    if (in.read((char*) &len, sizeof(len)))
    {
        out.name.resize(len);
        if (len > 0) in.read(&(out.name[0]), len);
        in.read((char*) &(out.add_year), sizeof(out.add_year));
    }
    return in;
}

ostream& operator<<(ostream &out, const details &in)
{
    int32_t len = in.name.size();
    out.write((char*) &len, sizeof(len));
    out.write(in.name.c_str(), len);
    out.write((char*) &(in.add_year), sizeof(in.add_year));
    return out;
}

const char * file = "students.dat";

int main()
{
    details x;

    ifstream ifile;
    ifile.open(file, ios_base::binary);
    if (ifile.is_open())
    {
        cout << "Contents of " << file << " is" << endl;
        while (ifile >> x)
        {
            cout << x.name << " - " << x.add_year << endl;
        }
        ifile.close();
    }

    cout << "Name:" << endl;
    getline(cin, x.name);
    cout << "Year added:" << endl;
    cin >> x.add_year;

    ofstream ofile(file, ios_base::app|ios_base::binary);
    if (!ofile.is_open())
    {
        cerr << "Can't open " << file << endl;
        exit(EXIT_FAILURE);
    }
    ofile << x;
    ofile.close();

    cin.get();
    return 0;
}