需要为之前创建的文件创建一个副本,其中包含 15 个随机数,并在此副本中将这些数字倒序写入。
我尝试用 for() 读取文件并写入数组,这也会用 for() 填充新创建的文件,但是 IDE 会在执行 for() 时立即停止脚本。
#include <stdio.h>
#include <stdlib.h>
int main(){
char a[20], sf[20], tf[20];
FILE *source, *target;
int i;
printf("Enter name of file to copy\n");
gets(sf);
source = fopen(sf, "r");
if (source == NULL){
printf("Press any key to exit...\n");
exit(1);
}
printf("Enter name of target file\n");
gets(tf);
target = fopen(tf, "w");
if (target == NULL){
fclose(source);
printf("Press any key to exit...\n");
exit(1);
}
for(i=0;i<15;i++){
fscanf(source, "%d", a[i]);
//printf("%d\n", a[i]);
}
for(i=15;i>0;i--){
fprintf(target, "%d\n", a[i]);
}
//printf("File copied successfully.\n");
return 0;
}
最佳答案
一些评论:
如评论中所述,您阅读的是 int,因此您需要一个 int 数组,而不是一个 char 数组来保存它们,目前你将写出具有未定义行为的a
如果你需要保存 15 个值,一个 15 的数组就足够了,20(假设 int)没用
从不使用gets,它已被弃用(多年来)因为危险,使用fgets不要冒险写在接收字符串之外,不要忘记删除可能的换行符
可能是输入文件和输出文件相同,所以在打开输出文件之前先读取并写入其内容
fscanf(source, "%d", a[i]);
无效,必须是fscanf(source, "%d", &a[i]) ;
检查 fscanf 的结果以管理输入文件中的错误情况
fprintf(target, "%d\n", a[i]);
必须是fprintf(target, "%d\n", a[i- 1]);
显式fclose输出文件更好,以防您稍后将程序转换为更复杂的程序
一个建议:
#include <stdio.h>
#include <string.h>
#define N 15
FILE * openIt(const char * msg, const char * dir)
{
char fn[256];
printf(msg);
if (fgets(fn, sizeof(fn), stdin) == NULL)
/* EOF */
return NULL;
char * p = strchr(fn, '\n');
if (p != NULL)
*p = 0;
FILE * fp = fopen(fn, dir);
if (fp == NULL)
fprintf(stderr, "cannot open '%s'\n", fn);
return fp;
}
int main()
{
FILE * fp;
if ((fp = openIt("Enter name of file to copy\n", "r")) == NULL)
return -1;
int a[N], i;
for (i = 0; i != N; ++i) {
if (fscanf(fp, "%d", &a[i]) != 1) {
fprintf(stderr, "invalid integer rank %d\n", i);
fclose(fp);
return -1;
}
}
fclose(fp);
if ((fp = openIt("Enter name of target file\n", "w")) == NULL)
return -1;
while (i--) {
fprintf(fp, "%d\n", a[i]);
}
fclose(fp);
return 0;
}
编译和执行:
pi@raspberrypi:/tmp $ gcc -pedantic -Wall -Wextra r.c
pi@raspberrypi:/tmp $ cat in
1 2 3 4 5
6 7 8 9 10
11 12
13
14
15
not read
pi@raspberrypi:/tmp $ ./a.out
Enter name of file to copy
in
Enter name of target file
out
pi@raspberrypi:/tmp $ cat out
15
14
13
12
11
10
9
8
7
6
5
4
3
2
1
pi@raspberrypi:/tmp $ ./a.out
Enter name of file to copy
out
Enter name of target file
out
pi@raspberrypi:/tmp $ cat out
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
pi@raspberrypi:/tmp $
关于复制文件并向后写入文件信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55479694/