一切文件、数据都是以字节为单位进行读写。
#include <stdio.h> #include <stdlib.h> int main() { int a = 1234; int b = 5; unsigned char *tmp = NULL; int ret = 0; FILE *fd = fopen("C:\\MinGW\\bin\\test.txt","w+"); printf("size of int is %d\n",sizeof(int)); if(!fd) { printf("open file failed!\n"); } if(!(ret=fwrite(&a,4,1,fd))) { printf("failed fwrite,ret is %d\n",ret); } printf("write ret is %d\n",ret); fclose(fd); fd = fopen("C:\\MinGW\\bin\\test.txt","r"); fread(&b,4,1,fd); tmp = (unsigned char*)&b; printf("now tmp[0] is %d\n",tmp[0]); printf("now tmp[1] is %d\n",tmp[1]); printf("now tmp[2] is %d\n",tmp[2]); printf("now tmp[3] is %d\n",tmp[3]); fclose(fd); system("pause"); return 0; }
其中核心测试数据1234,210,4对应的二进制数据分别如下:
1234 ->10011010010 210 -> 11010010 4 -> 100