简体   繁体   English

以二进制形式打开文件

[英]Opening File in binary form

I am trying to use C++ to open a file. 我正在尝试使用C ++打开文件。 The file can be of any type. 该文件可以是任何类型。 The thing that I am trying to do is to open the file as it is stored in the memory. 我要尝试做的是打开文件,因为它存储在内存中。

Suppose that it is a 1 byte text file and stored in the memory as 10000011 then I want to use C++ to open the file in this format, like how it is stored in the computer. 假设它是一个1字节的文本文件,并以10000011的形式存储在内存中,那么我想使用C ++以这种格式打开文件,就像它在计算机中的存储方式一样。

How to do so? 怎么做?

You can open file in binary format with calling fopen function like: 您可以通过调用fopen函数来以二进制格式打开文件,例如:

FILE* f = fopen(filename, "rb");

Now you can't read the file bit by bit, but you'll have to read it at least byte by byte (because byte is the smallest unit you should work with), eg: 现在您无法一点一点地读取文件,但是您必须至少逐个字节地读取文件(因为字节是您应该使用的最小单位),例如:

unsigned char value;
fread(&value, 1, 1, sizeof(unsigned char));

will read single byte of the file. 将读取文件的单个字节。 You can then access single bits by binary and operation (&), printing this value as binary (eg 0s and 1s) could be done like this: 然后,您可以通过二进制和运算符(&)访问单个位,可以按以下方式将此值打印为二进制值(例如0和1):

    printf("%d%d%d%d%d%d%d%d\n", 
           value & 0x80 ? 1 : 0, 
           value & 0x40 ? 1 : 0, 
           value & 0x20 ? 1 : 0, 
           value & 0x10 ? 1 : 0, 
           value & 0x8 ? 1 : 0, 
           value & 0x4 ? 1 : 0, 
           value & 0x2 ? 1 : 0, 
           value & 0x1 ? 1 : 0);

Of course these are C standard functions, you can use also C++ ones, for opening use: 当然这些是C标准函数,也可以使用C ++函数进行开放使用:

  ifstream file (filename, ios::in|ios::binary);

For reading you can use: 为了阅读,您可以使用:

  file.read(valueAddress, sizeInBytes);

And you should know how to print the stuff out (with cout). 而且您应该知道如何将这些内容打印出来(使用cout)。

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

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