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

來源:互聯網
上載者:User

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

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

將讀取wf.bin的0x13 byte處的值。

Method 1:使用fsetpos()

fsetpos.c / C

 1 /* 
2 (C) OOMusou 2011 http://oomusou.cnblogs.com
3
4 Filename : fsetpos.c
5 Compiler : Visual C++ 6.0
6 Description : how to get 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 c;
16
17 fp = fopen("./wf.bin", "rb");
18 if (!fp)
19 return 1;
20
21 pos = 0x13;
22 fsetpos(fp, &pos);
23
24 c = fgetc(fp);
25
26 printf("%x\n", c);
27
28 return 0;
29 }

21行

pos = 0x13;
fsetpos(fp, &pos);

直接使用fsetpos()將位置移動到0x13 byte處。

Method 2:使用fseek()

fseek.c / C

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

19行

fseek(fp, 0x13, SEEK_SET);

使用fseek()將位置移動到0x13 byte處,SEEK_SET表示從檔案開始處開始offset。

完整程式碼下載
fsetpos.7z (使用fsetpos())
fseek.7z (使用fseek())

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.