(筆記) 如何讀取binary file某個byte連續n byte的值? (C/C++) (C)

Abstract
通常公司為了保護其智慧財產權,會自己定義檔案格式,其header區會定義每個byte各代表某項資訊,所以常常需要直接對binary檔的某byte直接進行讀取,且連續幾個byte表示某一數值資訊。

Introduction
使用環境:Windows XP SP3 + Visual C++ 6.0 SP6

將讀取wf.bin的0x04 byte處的連續4 byte值。

Method 1:使用char array

ReadNByte1.c / C

 1 /* 
2 (C) OOMusou 2011 http://oomusou.cnblogs.com
3
4 Filename : ReadNByte1.c
5 Compiler : Visual C++ 6.0
6 Description : how to get n-byte value with n-byte position?
7 Release : oct.27,2011 1.0
8 */
9
10 #include <stdio.h>
11
12 int main() {
13 FILE *fp;
14 fpos_t pos;
15 unsigned char buff[4];
16
17 fp = fopen("./wf.bin", "rb");
18 if (!fp)
19 return 1;
20
21 pos = 0x04;
22 fsetpos(fp, &pos);
23
24 fread(buff, sizeof(char), 4, fp);
25
26 printf("0x%02x\n", buff[0]);
27 printf("0x%02x\n", buff[1]);
28 printf("0x%02x\n", buff[2]);
29 printf("0x%02x\n", buff[3]);
30
31 return 0;
32 }

24行

fread(buff, sizeof(char), 4, fp);

使用fread將4 byte讀進char array,因為單位是char,所以要讀進4個char。

Method 2:使用unsigned int

ReadNByte2.c / C

 1 /* 
2 (C) OOMusou 2011 http://oomusou.cnblogs.com
3
4 Filename : ReadNByte2.c
5 Compiler : Visual C++ 6.0
6 Description : how to get n-byte value with n-byte position?
7 Release : oct.27,2011 1.0
8 */
9
10 #include <stdio.h>
11
12 int main() {
13 FILE *fp;
14 fpos_t pos;
15 unsigned int buff;
16
17 fp = fopen("./wf.bin", "rb");
18 if (!fp)
19 return 1;
20
21 pos = 0x04;
22 fsetpos(fp, &pos);
23
24 fread(&buff, sizeof(unsigned int), 1, fp);
25 printf("0x%08x\n", buff);
26
27 return 0;
28 }

24行

fread(&buff, sizeof(unsigned int), 1, fp);

使用fread將4 byte讀進unsigned int,因為unsigned int已經是4 byte,所以只需讀進1個unsigned int即可。

實務上這種方式的應用較多。

完整程式碼下載
ReadNByte.7z

Conclusion
本文皆使用fsetpos(),史實上也可使用fseek(),請參考(筆記) 如何讀取binary file某個byte的值? (C/C++) (C)

See Also
(筆記) 如何讀取binary file某個byte的值? (C/C++) (C)

posted on 2011-10-27 23:35  真 OO无双  阅读(19367)  评论(0编辑  收藏  举报

导航