linux中把一个磁盘文件信息复制到另一个中,总是出问题
以下是源代码,实现的结果是,磁盘中的信息是隔一个字符复制的,不知道为什么,求指点,谢谢。
#include
#include
#include
main()
{
FILE *fp;
FILE *fp1;
char ch;
char filename[10];
char filename1[10];
char filepath[50];
char filepath1[100];
printf("give a file a filename: ");
scanf("%s",filename);
sprintf(filepath,"/socketTest/photo/%s",filename);
if((fp=fopen(filepath,"w+"))==NULL)
{
printf("cannot open the file <%s>\n",filename);
return 0;
}//if
ch=getchar();
printf("please input:\n");
ch=getchar();
while(ch!='#')
{
fputc(ch,fp);
ch=getchar();
}//while
fclose(fp);
printf("give another file a filename: ");
scanf("%s",filename1);
ch=getchar();
sprintf(filepath1,"/socketTest/photo/%s",filename1);
if((fp1=fopen(filepath1,"w+"))==NULL)
{
printf("cannot open the file <%s>\n",filename1);
return 0;
}//if
printf("the length of %s is %d\n",filename1,strlen(filepath1));
if((fp=fopen(filepath,"r"))==NULL)
{
printf("cannot open the file <%s>\n",filename);
return 0;
}//if
while(fgetc(fp)!=EOF)
{
printf("%c",fgetc(fp));
fputc(fgetc(fp),fp1);
}
fclose(fp1);
fclose(fp);
printf("\n file %s is ok!\n",filename1);
}//main
下面的代码使得字符指针fp一共向前移动了3次,不跳反而不正常了。
while(fgetc(fp)!=EOF)
{
printf("%c",fgetc(fp));
fputc(fgetc(fp),fp1);
}
fgetc(fp)
调用了3次...
1楼正解.
while(fgetc(fp)!=EOF)
{
printf("%c",fgetc(fp));
fputc(fgetc(fp),fp1);
}
这段代码,每一个fgetc的调用,就会引起fp中位置指针的向后移动,所以才会造成复制时的跳动。正确的代码应该是:
int c;
while((c = fgetc(fp))!=EOF)
{
//printf("%c",fgetc(fp));
fputc(c,fp1);
}
PS:几个建议:
1:变量起名要有意义,比如fpsrc,fpdst,这样别人一看就知道哪个是源文件,哪个是目标文件;
2:不要用sprintf,用snprintf;
while 循环函数调用多次