文件大小端转换:
int _tmain(int argc, _TCHAR* argv[])
{
FILE *pf = fopen("old.bin", "rb");
FILE *pfw = fopen("new.bin", "wb");
unsigned int data=0;
unsigned char *chr;
int ret = 0;
printf("data init: 0x%x\n", data);
if (NULL != pf && NULL != pfw)
{
while ((ret = fread(&data, 1, 4, pf)) == 4)
{
data = ((data & 0xff000000) >> 24)
| ((data & 0x00ff0000) >> 8)
| ((data & 0x0000ff00) << 8)
| ((data & 0x000000ff) << 24);
fwrite(&data, 1, 4, pfw);
}
printf("data: 0x%x\n", data);
printf("ret %d\n", ret);
chr = (unsigned char*)(&data);
for (int i=ret; i>0; i--)
{
fwrite(&chr[i], 1, 1, pfw);
}
fclose(pf);
fclose(pfw);
}
system("PAUSE");
return 0;
}
fread函数说明:
int _tmain(int argc, _TCHAR* argv[])
{
FILE *pf = fopen("uboot-gk7101-imx222.bin", "rb");
FILE *pfw = fopen("new.bin", "wb");
unsigned int data=0;
unsigned char chr[4] = {0};
int ret = 0;
if (NULL != pf && NULL != pfw)
{
while ((ret = fread(&data, 1, 4, pf)) == 4)
{
printf("data: 0x%x\n", data);
data = ((data & 0xff000000) >> 24)
| ((data & 0x00ff0000) >> 8)
| ((data & 0x0000ff00) << 8)
| ((data & 0x000000ff) << 24);
printf("data: 0x%x\n", data);
break;
}
fclose(pf);
printf("******************************************************************\n");
pf = fopen("uboot-gk7101-imx222.bin", "rb");
while ((ret = fread(&data, 4, 1, pf)) == 1)
{
printf("data: 0x%x\n", data);
data = ((data & 0xff000000) >> 24)
| ((data & 0x00ff0000) >> 8)
| ((data & 0x0000ff00) << 8)
| ((data & 0x000000ff) << 24);
printf("data: 0x%x\n", data);
break;
}
fclose(pf);
printf("******************************************************************\n");
pf = fopen("uboot-gk7101-imx222.bin", "rb");
while ((ret = fread(chr, 4, 1, pf)) == 1)
{
printf("chr: 0x%x%x%x%x\n", chr[3], chr[2], chr[1], chr[0]);
break;
}
fclose(pf);
printf("******************************************************************\n");
pf = fopen("uboot-gk7101-imx222.bin", "rb");
while ((ret = fread(chr, 1, 4, pf)) == 4)
{
printf("chr: 0x%x%x%x%x\n", chr[3], chr[2], chr[1], chr[0]);
break;
}
fclose(pf);
fclose(pfw);
}
system("PAUSE");
return 0;
}
data: 0x474b3731
data: 0x31374b47
******************************************************************
data: 0x474b3731
data: 0x31374b47
******************************************************************
chr: 0x474b3731
******************************************************************
chr: 0x474b3731
fread(buf, size, count, pf)
buf:接收数据的内存地址
size:要读的每个数据项的字节数
count:要读count个数据项,每个数据项size个字节(是正确读取时的返回值)
pf:文件句柄
fread(buf, 4, 1, pf) //读取数据项大小为4,只读取1个数据项。返回值为1
fread(buf, 1, 4, pf) //读取数据项大小为1,读取4个数据项。返回值为4