題目:利用字符讀寫函數實現文件的拷貝
#include<stdio.h>
#include<stdlib.h>
void main(int argc,char *argv[])
{
FILE *input,*output;
if(argc!=3) //一定要輸入三個參數,可執行文件 ,源文件名 ,目標文件名
{
printf("the number of arguments not correct\n");
printf("\n Usage:可執行文件名 source-file dest-file");
exit(0);
}
if((input=fopen(argv[1],"r"))==NULL) //源文件不可讀
{
printf("can not open source file\n");
exit(0);
}
if((output=fopen(argv[2],"w"))==NULL) //目標文件不可寫
{
printf("can not create destination file\n");
exit(0);
}
for(;(!feof(input));) //feof函數用於判斷文件是否結束,在讀文件時,如果遇到文件尾,則返回爲1,否則返回0
fputc(fgetc(input),output);//fgetc函數時在input所指向的文件中,讀取一個字節的數據,同時讀寫位置指向向後移動,指向下一個字符,讀寫正確時,返回讀到的字節數,讀到文件尾或出錯,返回EOF(-1),fputc(int c,flie *fp)將形參c表示的字符數據輸出到文件指針fp所指向的文件中,同時讀寫位置指針指向下一個寫入位置。
fclose(input); //關閉文件
fclose(output);
}
運行結果:
源文件:
目標文件: