改进以下代码(用于复制文件)#include<stdio.h> int main() { FILE *f1; FILE *f2; char oriname[20]; char objname[20]; printf("please enter the name of the original file:\n"); scanf("%s",oriname); printf("please enter the name of the objective file:\n"); scanf("%s",objname); f1 = fopen(oriname,"r"); if(f1 == NULL) { printf("ORI FILE OPEN ERROR!\n"); } char str[6][20]; int i; for(i=0;i<6;i++) { fscanf(f1,"%s",str[i][20]); } fclose(f1); f2 = fopen(objname,"w"); if(f2 == NULL) { printf("OBJ FILE OPEN ERROR!\n"); } for(i=0;i<6;i++) { fprintf(f2,"%s",str[i][20]); } fclose(f2); return 0; }
时间: 2023-11-27 15:53:37 浏览: 75
SeqList.h #include <stdio.h> //包含标准输入输出流的头文件 #include <assert.h
改进后的代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *f1;
FILE *f2;
char oriname[20];
char objname[20];
printf("Enter the name of the original file: ");
scanf("%s", oriname);
printf("Enter the name of the objective file: ");
scanf("%s", objname);
f1 = fopen(oriname, "r");
if (f1 == NULL) {
printf("Error opening original file!\n");
exit(1);
}
char str[6][20];
int i;
for (i = 0; i < 6; i++) {
if (fscanf(f1, "%s", str[i]) != 1) {
printf("Error reading from original file!\n");
exit(1);
}
}
fclose(f1);
f2 = fopen(objname, "w");
if (f2 == NULL) {
printf("Error opening objective file!\n");
exit(1);
}
for (i = 0; i < 6; i++) {
if (fprintf(f2, "%s ", str[i]) < 0) {
printf("Error writing to objective file!\n");
exit(1);
}
}
fclose(f2);
printf("File copied successfully!\n");
return 0;
}
```
改进说明:
1. 添加了头文件stdlib.h,以便使用exit函数。
2. 将输入提示语句改成了更加友好的语言。
3. 对文件打开、读取、写入等操作进行了错误检查,保证程序健壮性。
4. 读取和写入文件的方式有所修改,以确保正确性。
阅读全文