C語言練習-文件讀寫
要求:
設在文件a.txt和文件b.txt中分別存有兩個字符串,設計一個程序將這兩個字符串按依序交叉的方式合併爲一個字符串(例如“aaaaa”與“bbb”的合併結果爲“abababaa”,而“bbb”與“aaaaa”的合作結果爲“ bababaa”,)並將結果存入文件a.txt中。
分析:
首先定義兩個文件指針 分別指向a和b a以讀寫的方式打開,b以讀的方式打開。
再定義一個新的指針 指向c文件 將a和b所讀的東西,依次交錯寫入c中。
再次讀入c中所寫的東西,寫入a中。
關閉a b c 所對應的文件指針 釋放資源。
代碼:
#include<stdio.h>
#include<stdlib.h>
main()
{
FILE *fa;
FILE *fb;
FILE *fc;
char fna[10],fnb[10],fnc[10];
char ch;
printf("Please input the first file name!");
scanf("%s",fna);
printf("Please input the second file name!");
scanf("%s",fnb);
printf("Please input the third file name!");
scanf("%s",fnc);
if((fa=fopen(fna,"r+"))==NULL)
{
printf("Cannot open the file %s!",fna);
exit(0);
}
if((fb=fopen(fnb,"r"))==NULL)
{
printf("Cannot open the file %s!",fnb);
exit(0);
}
if((fc=fopen(fnc,"w+"))==NULL)
{
printf("Cannot open the file %s!",fnc);
exit(0);
}
while(!feof(fa))
{
ch=fgetc(fa);
fputc(ch,fc);
if(!feof(fb))
{
ch=fgetc(fb);
fputc(ch,fc);
}
}
rewind(fa);
rewind(fc);
while(!feof(fc))
{
ch=fgetc(fc);
fputc(ch,fa);
}
fclose(fa);
fclose(fb);
fclose(fc);
}