3

如何在 c/c++ 中读取不是简单文本文件的文件内容?例如,我想读取 .jpg/.png/.bmp 等图像文件并查看某个索引处的值,以检查它是什么颜色?或者如果我有一个 .exe/.rar/.zip 并且想知道不同索引中存储的值是什么?我知道c风格的阅读文件,这是

FILE *fp;

fp = fopen("example.txt","r"); /* open for reading */

char c;

c = getc(fp) ;

我想知道我是否将“example.txt”替换为“image.png”左右,它会起作用吗?我会得到正确的数据吗?

4

3 回答 3

9

When you open a non-text file, you'll want to specify binary (untranslated) mode:

FILE *fp = fopen("example.png", "rb");

In a typical case, you do most of your reading from binary files by defining structs that mirror the structures in the file, and then using fread to read from the file into the structure (but this has to be done carefully, to ensure that things like padding in the struct don't differ between the representation in-memory and on-disk).

于 2012-04-19T06:03:07.043 回答
2

您需要以二进制模式打开文件。这允许您以“原始”模式读取字节,其中它们与文件中的内容保持不变。

但是,确定特定像素的颜色等需要您完全理解文件中字节的含义以及它们是如何为正在读取的文件排列的。这第二个要求要困难得多。您需要对该文件类型的格式进行一些研究才能做到这一点。

于 2012-04-19T06:01:14.470 回答
1

binary mode是的,你可以在c中打开任何文件。如果您有兴趣,那么您还可以阅读任何此类非文本文件的第一个字节。

在大多数情况下,所有不同的文件格式都有一些固定的标题,因此您可以根据它来识别该文件的类型。

打开任何 matroska(.mkv) 文件并读取第一个 4 字节,您将永远拥有这个

0x1A   0x45   0xDF   0xA3

您还可以 hexdump在 linux 的二进制表示实用程序中查看任何文件

===================== 编辑:

such as .jpg/.png/.bmp and see the value at certain index,to 
check what colour it is?

在这里您需要了解该文件的格式,并在此基础上您可以知道哪个地方的数据表明了什么信息..!!!

于 2012-04-19T06:23:31.993 回答