对二进制文件的复制,修改

对二进制文件的复制,就是rb方式打开source文件,以wb方式打开target文件。
#include
#include
void main()
{
	FILE *fp;
	if((fp=fopen("E:\\class\\banjiname.dat","rb"))==NULL)
	{
		printf("error\n");
		exit(1);
	}
	FILE *fp1;
	if((fp1=fopen("E:\\class\\banjiname_new.dat","wb"))==NULL)
	{
		printf("error\n");
		exit(1);
	}
	char banjiname[20];
	while(fread(banjiname,20,1,fp))
	{
		fwrite(banjiname,20,1,fp1);
	}
	fclose(fp);
	fclose(fp1);

}
对二进制文件的修改,就是在复制的前提下,添加一个筛选过程,将要去掉的内容continue掉

#include #include #include void main() {  FILE *fp;  if((fp=fopen("E:\\class\\banjiname.dat","rb"))==NULL)  {   printf("error\n");   exit(1);  }  FILE *fp1;  if((fp1=fopen("E:\\class\\banjiname_new.dat","wb"))==NULL)  {   printf("error\n");   exit(1);  }  char banjiname[20];  while(fread(banjiname,20,1,fp))  {   if(strcmp(banjiname,"jike1")!=0)    fwrite(banjiname,20,1,fp1);   else    continue;  }  fclose(fp);  fclose(fp1);

}

必要时利用remove删除fp,把fp用rename更名为fp1;

 

 

所谓对二进制文件的修改,就是读取到target,利用fseek把指针定位到target前,然后利用fwrite写入新内容

#include #include #include void main() {  char ch[20]="jikeyes";  char ch1[20]="jike2";  char banjiname_1[20];  FILE *fp2;  if((fp2=fopen("E:\\class\\banjiname.dat","rb+"))==NULL)//只读方式打开文件   {    printf("error\n");    exit(1);   }  while(fread(banjiname_1,20,1,fp2))  {   if(strcmp(ch1,banjiname_1)!=0)    continue;   else   {    fseek(fp2,-20L,1);    fwrite(ch,20,1,fp2);    break;   }   }  fclose(fp2); }

 

 
  

 

 
 

你可能感兴趣的:(c,c++)