C程序设计 (第四版) 谭浩强 例10.2
例10.2 将一个磁盘文件中的信息复制到另一个磁盘文件中。
IDE工具:VS2010
Note: 使用不同的IDE工具可能有部分差异。
代码块
方法:使用指针,函数的模块化设计,动态分配内存
说明:这里准备先写入的文件名称为Test.txt,准备复制到Test1.txt文件中,文件都已经存在于该项目目录下,。
#include <stdio.h>
#include <stdlib.h>
void initialFile(char **name1, char **name2){
*name1 = (char*)malloc(80 * sizeof(char));
*name2 = (char*)malloc(80 * sizeof(char));
}
void inputFileName(FILE **file, char *name, int num){
printf("Enter File%d Name: ", num);
scanf("%s", name);
char *sign = '\0';
if(num == 1){
sign = "r";
}
if(num == 2){
sign = "w+";
}
*file = fopen(name, sign);
if(*file == NULL){
perror("Cannot open this file");
system("pause");
exit(0);
}
}
void inputFile(FILE **file, char *name){
char ch;
*file = fopen(name, "w");
ch = getchar();
printf("Enter String (End with EOF): ");
while((ch = getchar()) != EOF){
fputc(ch, *file);
putchar(ch);
}
printf("\n");
fclose(*file);
}
void fileCopy(FILE **file1, FILE **file2, char *name1, char *name2){
*file1 = fopen(name1, "r");
char ch;
ch = getchar();
while(!feof(*file1)){
ch = fgetc(*file1);
fputc(ch, *file2);
putchar(ch);
}
fclose(*file1);
fclose(*file2);
putchar(10);
}
void freeFile(char **name1, char **name2){
free(*name1);
free(*name2);
}
int main(){
FILE *file1 = NULL;
FILE *file2 = NULL;
char *name1 = NULL;
char *name2 = NULL;
initialFile(&name1, &name2);
inputFileName(&file1, name1, 1);
inputFile(&file1, name1);
inputFileName(&file2, name2, 2);
fileCopy(&file1, &file2, name1, name2);
freeFile(&name1, &name2);
system("pause");
return 0;
}