首页 > 解决方案 > 只读取二进制文件的第一行

问题描述

函数应该创建复杂(我的结构)向量,而不是将其保存到二进制文件中,然后从二进制文件中读取它。问题是它只在第一行读得很好。

结构很好。除了阅读,一切都很好。这些是读取和写入函数:

void saveVectorBin(vector<Complex> &v, const string filename) {
    ofstream output;
    output.open(filename, ios::binary);
    if (output)
    {
        for (auto i: v) {
            output.write(reinterpret_cast<char*> (&i), sizeof(i));
            output << endl;
        }
        cout << "Wektor zapisany do pliku " << filename << endl;
        output.close();
    }
    else cout << endl << "BLAD TWORZENIA PLIKU BIN" << endl;
}

vector<Complex> readComplexVectorBin(const string &filename) {
    vector<Complex> v;
    ifstream input;
    input.open(filename, ifstream::binary);
    if (input) {
        Complex line;
        while (input.read(reinterpret_cast<char*> (&line), sizeof(Complex))) {
            v.push_back(Complex(line));
        }
        input.close();
    }
    else cout << endl << "BLAD ODCZYTU PLIKU" << endl;
    return v;
}

应该显示:

26.697 + 7.709i
20.133 + 23.064i
9.749 + 8.77i 

相反,它显示:

26.697 + 7.709i
1.43761e-57 + 1.83671e-43i
1.26962e+306 + -2.39343e-259i

标签: c++binary

解决方案


您的问题是您要在二进制文件中插入换行符。

output << endl;

将数据添加到您的文件中

while (input.read(reinterpret_cast<char*> (&line), sizeof(Complex))) {
    v.push_back(Complex(line));
}

没有考虑到。您要么需要摆脱output << endl;写作循环(最简单的解决方案),要么读入并丢弃阅读循环中的换行符(最难的解决方案)。


推荐阅读