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