file io-如何在c++中读取二进制数据
file io - how can i read binary data in c++?
我需要在C++中读写二进制数据。我使用from ofstream
和ifstream
类,但它不能读取一些字符,如9,13,32。如果有其他方法可以读写主题。
使用std::ios::binary
标志打开文件,然后使用.read(buffer,length);
和.write(buffer,length);
,而不是流式操作符。
这里有一些例子:
https://cplusplus.com/reference/istream/istream/read/
https://cplusplus.com/reference/ostream/ostream/write/
这里有一个程序可以做到这一点:
#include <iostream>
#include <fstream>
int main(int argc, const char *argv[])
{
if (argc < 2) {
::std::cerr << "Usage: " << argv[0] << "<filename>n";
return 1;
}
::std::ifstream in(argv[1], ::std::ios::binary);
while (in) {
char c;
in.get(c);
if (in) {
::std::cout << "Read a " << int(c) << "n";
}
}
return 0;
}
下面是一个在Linux中运行的例子:
$ echo -ne 'x9xdx20x9xdx20n' >binfile
$ ./readbin binfile
Read a 9
Read a 13
Read a 32
Read a 9
Read a 13
Read a 32
Read a 10
这是一个基本示例(没有任何错误检查!):
// Required STL
#include <fstream>
using namespace std;
// Just a class example
class Data
{
int a;
double b;
};
// Create some variables as examples
Data x;
Data *y = new Data[10];
// Open the file in input/output
fstream myFile( "data.bin", ios::in | ios::out | ios::binary );
// Write at the beginning of the binary file
myFile.seekp(0);
myFile.write( (char*)&x, sizeof (Data) );
...
// Assume that we want read 10 Data since the beginning
// of the binary file:
myFile.seekg( 0 );
myFile.read( (char*)y, sizeof (Data) * 10 );
// Remember to close the file
myFile.close( );
相关文章:
- 正在读取二进制文件(is_open)
- 如何从dicom文件中读取二进制数据
- C++用于从流中读取二进制值的任何标准库
- readsome() 适合在 Windows 上读取二进制数据吗?
- 读取二进制文件并解释为整数
- 读取二进制文件直到结束 c++
- 如何在标准c ++中流式传输/读取二进制文件的中间部分并写入另一个文件?
- 读取二进制文件的惯用C++17标准方法是什么
- 从末尾读取二进制文件
- C++逐个字符读取二进制文件字符
- 读取二进制文件大小的短自上周以来停止工作
- 读取二进制文件时出现问题
- 读取二进制文件时如何输出?
- C++:如何在线程中读取二进制文件并将其写入另一个线程?
- 在C 中读取二进制文件会返回意外值
- 尝试读取二进制文件会清除文件本身
- C 读取二进制文件
- 通过C 读取二进制文件的问题
- 用ifstream read()读取二进制的结构
- ifstream读取二进制文件在发行模式下工作,但在调试模式下不使用