用c++读写二进制信息

Reading and writing binary information with C++

本文关键字:信息 二进制 读写 c++      更新时间:2023-10-16

我在读写二进制信息时遇到了一些麻烦。我可以成功地将一个简单的字符串写入文本文件,在本例中,我的文件'output.dat'包含句子"Hello, this is a sentence"。

然而,我不能读回我的信息。我找不到问题所在。我打算稍后更改从二进制文件中读取的信息的每个字节,以便将值作为字符串返回。

谢谢你提供的任何帮助。

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void write(const string &input) {
    fstream output("output.dat", ios::out | ios::binary);
    if (output.is_open()) {
        output.write(input.c_str(), input.size());
        output.close();
    }
}
string read(const string &fname) {
    int size;
    char* buffer;
    fstream input(fname, ios::in | ios::binary);
    if (input.is_open()) {
        input.seekg(0, ios::end);
        size = input.tellg();
        input.seekg(0, ios::beg);
        buffer = new char[size];
        input.read(buffer, size);
        input.close();
    }
    string result(buffer);
    return result;
}
int main () {
    cout << read("output.dat") << endl;
    system("pause");
    return 0;
}

bug在这里

char* buffer;
input.read(buffer, size);

您正在读取buffer指向的内存。

但是它指向哪里呢?指针buffer未初始化

如果你知道你需要多少空间,像这样的方法就会奏效。

std::vector<char> buffer(size);
input.read(&buffer.front(), size);

我真的无法理解这段代码中出了什么问题,因为它看起来很好,并且对我来说很好。然而,您正在分配的缓冲区缺少空终止符来标记字符字符串的结束。改成这样:

buffer = new char[size+1];
input.read(buffer, size);
buffer[size] = 0;