Reading the contents of a file other than a .txt file.

How can I read the contents of a file that is not a plain text file in c / C ++? For example, I want to read an image file, for example .jpg / .png / .bmp, and look at the value in a specific index to check what color it is? or if I have .exe / .rar / .zip and want to know what value is stored at different indexes? I know about c style reading file which

FILE *fp;

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

char c;

c = getc(fp) ;

I want to know if I replaced example.txt with "image.png" or so, will it work? Will I get the correct data?

+3
source share
3 answers

You will need to open the file in binary mode. This allows you to read bytes in raw mode, where they do not change from what was in the file.

, .. , . . .

+2

, () :

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

, , , fread ( , , , ).

+8

ya ofcorse binary mode c. , 1- .

In most cases, all different file formats have a fixed header, so based on this you can determine the type of this file.

Open any matroska file (.mkv) and read the 1st 4th byte, you will always have this

0x1A   0x45   0xDF   0xA3

you can also see any file in binary representation hexdumpin linux

====================== Edit:

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

here you need to understand the format of this file and based on this you can find out in what places the data indicates what information .. !!!

+1
source

All Articles