文件拷贝程序(命令行模式,用户交互模式)---C prime plus 13章练习题

//命令行
# include <stdio.h> # include <stdlib.h> # define BUFSIZE 2048 void write_in(FILE* source, FILE* dest); int main(int argc, char* argv[]) { FILE* fa; //一个指向目标文件,一个指向源文件 FILE* fs; int ch; if (argc != 3) { printf("Your argument is wrong.\n"); exit(EXIT_FAILURE); } if ((fs = fopen(argv[1], "rb")) == NULL) //以二进制模式打开文件 { fprintf(stdout, "Can't open the source file %s.\n", argv[1]); exit(0); } if ((fa = fopen(argv[2], "w+b")) == NULL) { fprintf(stdout, "Can't open the aim file %s.\n", argv[2]); exit(0); } while ((ch = getc(fs)) != EOF) putc(ch,fa); puts("DONE."); fclose(fa); //可以添加检测是否关闭了文件的语句 fclose(fs); return 0; }
//交互的方式
# include <stdio.h> # include <stdlib.h> # include <string.h> # include <ctype.h> # define SLEN 20 char* s_gets(char *st, int n); int main() { FILE* fa; //一个指向目标文件,一个指向源文件 FILE* fs; int ch; char source[SLEN]; char target[SLEN]; puts("Enter the name of the source file."); s_gets(source, SLEN); if ((fs = fopen(source, "r")) == NULL) //以文本模式 { fprintf(stdout, "Can't open the source file %s.\n", source); exit(0); } puts("Enter the name of the target file."); s_gets(target, SLEN); if (strcmp(source, target) == 0) { printf("Can't copy the file to himself."); exit(EXIT_FAILURE); } if ((fa = fopen(target, "w+")) == NULL) { fprintf(stdout, "Can't open the target file %s.\n", target); exit(0); } while ((ch = getc(fs)) != EOF) { putc(toupper(ch), fa); //将文本转为大写 } fclose(fs); rewind(fa); while ((ch = getc(fa)) != EOF) putchar(ch); puts("DONE."); fclose(fa); return 0; } char * s_gets(char *st, int n) { char* ret_val; char* find; ret_val = fgets(st, n, stdin); if (ret_val) { find = strrchr(st, '\n'); if (find) *find = '\0'; else while (getchar() != '\n') continue; } return ret_val; }

 

上一篇:2022.01.31刷题


下一篇:算法竞赛—欧拉筛素数(线性筛)