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

來源:互聯網
上載者:User

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

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

將寫入wf.bin的0x33 byte處的連續4 byte值。

 1 /* 
2 (C) OOMusou 2011 http://oomusou.cnblogs.com
3
4 Filename : WriteNByte.c
5 Compiler : Visual C++ 6.0
6 Description : how to write n byte value with n-byte position?
7 Release : oct.31,2011 1.0
8 */
9
10 #include <stdio.h>
11
12 int main() {
13 FILE *fp;
14 int filesize;
15 unsigned char buff[4];
16
17 fp = fopen("./wf.bin", "rb+");
18 if (!fp) {
19 fclose(fp);
20 return -1;
21 }
22
23 buff[0] = 0xAC;
24 buff[1] = 0xFF;
25 buff[2] = 0x1B;
26 buff[3] = 0xAA;
27
28 fseek(fp, 0x33, SEEK_SET);
29 fwrite(buff, sizeof(unsigned char), 4, fp);
30
31 fclose(fp);
32
33 return 0;
34 }

15行

unsigned char buff[4];

宣告4 byte char array。

17行

fp = fopen("./wf.bin", "rb+");

由於要修改目前開啟的binary f ile,所以使用rb+,詳細請參考(筆記) 如何寫入binary file某個byte的值? (C/C++) (C)。

23行

buff[0] = 0xAC;
buff[1] = 0xFF;
buff[2] = 0x1B;
buff[3] = 0xAA;

分別設定每個byte的值。

28行

fseek(fp, 0x33, SEEK_SET);

使用fseek將binary file的檔案位置移到0x33處,其中SEEK_SET表示offset是從檔頭開始。

29行

fwrite(buff, sizeof(unsigned char), 4, fp);

正式使用fwrite將buff寫入檔案,由於單位是unsigned char,所以size為4。

See Also
(筆記) 如何寫入binary file某個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.