//创建两个已含内容的源文件scr.txt和目标文件dst.txt,要求输入文件名。将源文件内容加到目标文件内容的后面。
//建立两个子函数,一个用于追加内容,一个用于输出追加后这两个文件的内容
#include<stdio.h>
#include<stdlib.h>
int add(FILE *in,FILE *out) //追加函数
{
int x=0;
char ch;
while(!feof(in))
{
ch=fgetc(in);
fputc(ch,out);
x++;
}
return x;
}
int sight(FILE *fp) //显示函数
{
int x=0;
char ch;
while(!feof(fp))
{
ch=fgetc(fp);
putchar(ch);
x++;
}
printf("\n");
return x;
}
int main()
{
int x,y,z; //用于接收函数返回值
FILE *in,*out;
char scr[10],dst[10];
printf("请输入源文件和目标文件的名称:\n");
gets(scr);
gets(dst);
if((in=fopen(scr,"r"))==NULL) //打开源文件
{
printf("无法打开scr.txt文件");
exit(0);
}
if((out=fopen(dst,"a+"))==NULL) //打开目标文件
{
printf("无法打开dst.txt文件");
exit(0);
}
x=add(in,out);
if(x==0)
printf("文件追加失败!");
else
{
rewind(in);
rewind(out); //让两个文件指针移回文件开头
y=sight(in); //分别输出两个文件的内容
z=sight(out);
}
if(x!=-1&&y!=-1)
printf("文件读取成功!");
else
printf("文件读取失败!");
fclose(in);
fclose(out);
return 0;
}
文件名的输入和文件追加
最新推荐文章于 2024-02-29 23:38:25 发布