用c++读写二进制信息
Reading and writing binary information with C++
我在读写二进制信息时遇到了一些麻烦。我可以成功地将一个简单的字符串写入文本文件,在本例中,我的文件'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;
相关文章:
- 将对象信息保存到二进制文件中
- 将文件信息(字符数组)嵌入到编译的二进制文件中
- 从一个二进制文件中读取信息,并写入另一个二进制文件
- (C++) 如何从要存储在结构数组中的二进制文件中读取.dat信息?
- 正在从C 二进制保险箱中剥离某些信息
- C ++,当我读取二进制文件时,我得到重复的信息
- 通过将结构信息从二进制文件读取到数组中,然后返回到文件C
- 加载格式化的二进制文件并将信息分配给结构 c++
- 用一些信息注释C++二进制文件
- 如何将信息从二进制数据文件读取到结构c 的数组中
- 二进制不是使用 Visual Studio 2008 中的调试信息构建的
- 二进制文件和兼容标准信息—C++/JAVA
- 大多数为 Qt 5.3.2 编译的二进制文件都是在没有调试信息的情况下构建的
- 如何在二进制文件(.net或非托管文件)中注入/更新Version和其他详细信息
- 如何将二进制文件中的信息发送到屏幕AND外部文件
- 使用条带是否删除二进制文件上的RTTI信息
- 创建一个二进制文件,向其中添加信息,并从中读取所有记录(电话簿)
- 访问基于二进制格式文档的特定二进制信息
- 获取、修改二进制文件的信息
- 我怎么能包括调试信息在我的二进制文件