在工作时候,遇到需要把一个文件中所有的字节,每两个字节交换一个位置,例如第一个字节和第二个字节交换位置,第三个和第四个字节交换一下位置,以此类推。
在此特作下记录。
#include "stdio.h"
#include "string.h"
#include "malloc.h"
int main(void)
{
FILE *fin;
FILE *fout;
void *fBuffStart = NULL;
void *fBuffEnd = NULL;
unsigned long fileSize = 0;
unsigned short *pDouble = NULL;
unsigned char *pSingle = NULL;
fin = fopen("test.mbp", "rb"); //打开文件
fseek(fin, 0L, SEEK_END); //获取字节数
fileSize = ftell(fin);
fseek(fin, 0L, SEEK_SET);
fBuffStart = (unsigned char *)malloc(fileSize); //申请内存
memset(fBuffStart, 0, fileSize); //清零
fread(fBuffStart, 1, fileSize, fin); //把内容读入到fBuffStart
fclose(fin); //关闭文件指针
fBuffEnd = (unsigned char *)fBuffStart + fileSize;
pDouble = (unsigned short *)fBuffStart;
fout = fopen("out.dat", "wb"); //打开输出文件
while (pDouble != fBuffEnd)
{
pSingle = (unsigned char *)pDouble;
fwrite(pSingle + 1, 1, 1, fout);
fwrite(pSingle, 1, 1, fout);
pDouble++;
}
fclose(fout); //关闭文件指针
free(fBuffStart); //释放内存
return 0;
}
转载请注明:guanjianhe的博客 » 每两个字节交换