简体   繁体   English

用C ++读写二进制信息

[英]Reading and writing binary information with C++

I'm having some trouble reading and writing binary information. 我在读写二进制信息时遇到了一些麻烦。 I can successfully write a simple string to a text file, in this case, my file 'output.dat' contains the sentence "Hello, this is a sentence". 我可以成功地将一个简单的字符串写入文本文件,在这种情况下,我的文件“ output.dat”包含句子“ Hello,这是一个句子”。

However, I cannot read my information back. 但是,我无法阅读我的信息。 I cannot identify the problem. 我无法确定问题所在。 I intend to change every byte of the information read from the binary file later on so returning the value as a string helps. 我打算稍后更改从二进制文件读取的信息的每个字节,因此将值作为字符串返回会有所帮助。

Thanks for any help you can provide. 感谢您的任何帮助,您可以提供。

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

The bug is here. 错误在这里。

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

You're reading to the memory that buffer is pointing to. 您正在读取buffer所指向的内存。

But where is it pointing to? 但是它指向哪里呢? The pointer buffer has never been initialized. 指针buffer从未初始化。

If you know how much space you need, an approach like this will work. 如果您知道需要多少空间,则可以使用这种方法。

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

I really cannot understand what is going wrong in this code, as it looks fine, and works fine with me. 我真的不明白该代码出了什么问题,因为它看起来不错,并且可以正常工作。 Nevertheless, the buffer you are allocating is missing the null terminator to mark char-string end. 但是,您正在分配的缓冲区缺少用于标记char-string结尾的空终止符。 Just change it to this: 只需将其更改为:

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

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

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