【发布时间】:2013-06-18 18:39:56
【问题描述】:
我需要一个 C 程序将一个文件的内容复制到另一个文件,同时满足以下条件:
1.) 我们从中读取数据的文件可能存在也可能不存在。
2.) 数据被复制到的文件可能存在也可能不存在。
如果文件存在,则直接复制数据,如果文件不存在,应该有一个选项创建文件,输入数据,然后将文件内容复制到另一个文件。
我编写了以下代码,
目前我修改的代码是:
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
void main()
{
FILE *f1,*f2;
char c;
char name1[20],name2[20];
clrscr();
setvbuf(stdout, 0, _IONBF, 0);
printf("\nEnter the source file name :");
scanf("%s",name1);
if((f1=fopen(name1,"r"))==NULL)
{
fclose(f1);
f1=fopen(name1,"w");
printf("\nThe specified file does not exist \nNew file will be created");
printf("\nEnter the data for the new file : ");
while((c=getchar())!=EOF)
{
putc(c,f1);
}
fclose(f1);
}
f1=fopen(name1,"r");
printf("\nEnter the destination file name :");
scanf("%s",name2);
f2=fopen(name2,"w+");
while((c=getc(f1))!=EOF)
{
putc(c,f2);
}
rewind(f1);
rewind(f2);
printf("The data in the source file is :\n");
while((c=getc(f1))!=EOF)
{
printf("%c",c);
}
printf("\nThe data in the destination file is :\n");
while((c=getc(f2))!=EOF)
{
printf("%c",c);
}
fclose(f1);
fclose(f2);
fflush(stdin);
getch();
}
但程序只有在源文件已经存在时才能正常工作。如果我创建一个新文件,则不会对目标文件名进行任何输入,并且目标文件文件中的数据为空白。那我现在该怎么办?
我应该修改什么以使其工作? 建议我您选择的任何代码...谢谢!
【问题讨论】:
-
究竟是什么不起作用? “它不起作用”是非信息性的。
-
如果我创建一个新文件,那么目标文件名不会被输入并且目标文件文件中的数据是空白的。
标签: c file copy file-handling copying