简体   繁体   English

仅读取二进制文件的第一行

[英]Reading good only first line of binary file

Functions should create Complex (my structure) vector, than save it to binary file and than read it from binary file. 函数应创建“复杂”(我的结构)矢量,然后将其保存到二进制文件并从二进制文件读取它。 The problem is that it reads good only first line. 问题在于它只读取第一行。

The structure is good. 结构很好。 Everything besides reading is working well. 除了阅读外,其他所有东西都运行良好。 These are read and write functions: 这些是读写功能:

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

Should show: 应显示:

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

Instead it shows: 相反,它显示:

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

Your issue is that you are inserting a newline into a binary file. 您的问题是您要在二进制文件中插入换行符。

output << endl;

adds data to your file that 将数据添加到您的文件中

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

fails to take into consideration. 没有考虑到。 You either need to get rid of output << endl; 您要么需要摆脱output << endl; in your writing loop (easiest solution) or read in and discard the newline in your reading loop (hardest solution). 在您的编写循环中(最简单的解决方案),或者在您的阅读循环中读取并丢弃换行符(最困难的解决方案)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM