我试图完成此练习:
使用fscanf()
和fprintf()
函数执行一个程序,编写从文件输入中获取的一些数字,逐个读取值,打印增加1的值并在文件中重写它们。
这是我做的:
include <stdio.h>
#include <cstdlib>
int main()
{
FILE *fp_1, *fp_2;
int n, num, num_inc, i;
fp_1 = fopen("output.txt", "w");
if (fp_1 == NULL) {
printf("Error");
return 1;
}
printf("How many values you want to write? ");
scanf("%i", &n);
for(i=0; i<n; i++) {
printf("Write the %i number: ", i+1);
scanf("%i", &num);
fprintf(fp_1, " %i ", num);
}
printf("Values read from file:\n");
fp_2 = fopen("output.txt", "r");
if(fp_2 == NULL) {
printf("Error");
return 2;
}
i = 0;
while(!feof(fp_2) && i<n) {
fscanf(fp_2, " %i ", &num);
num_inc = num+1;
fprintf(fp_1, " %i ", num_inc);
printf("%i value read is: %i\n", i+1, num_inc);
i++;
}
fclose(fp_1);
fclose(fp_2);
system("pause");
}
这是输出:
How many values you want to write? 5
Write the 1 number: 32
Write the 2 number: 124
Write the 3 number: 55646
Write the 4 number: 32
Write the 5 number: 112
Values read from file:
1 value read is: 113.
问题在于只读取了一个值。
谢谢!
答案 0 :(得分:1)
尝试在fp_1上执行fclose,然后再次以fp_2打开文件。
答案 1 :(得分:0)
关键是使用另一个文件进行第二次输出。
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *input_file, *output_file;
int n, num, num_inc, i;
input_file = fopen("input.txt", "w+"); // Actually it is the input for the next step.
if (input_file == NULL) {
printf("Error");
return 1;
}
printf("How many values you want to write? ");
scanf("%i", &n);
for (i = 0; i < n; i++) {
printf("Write the %i number: ", i + 1);
scanf("%i", &num);
fprintf(input_file, " %i ", num);
}
rewind(input_file); // Rewind to the beginning to perform reading.
output_file = fopen("output.txt", "w"); // The name of the output file (must be different from the input one).
if (output_file == NULL) {
printf("Error");
return 2;
}
printf("Values read from file:\n");
i = 0;
while (!feof(output_file) && i < n) {
fscanf(input_file, " %i ", &num);
num_inc = num + 1;
fprintf(output_file, " %i ", num_inc);
printf("%i value read is: %i\n", i+1, num_inc);
i++;
}
fclose(input_file);
fclose(output_file);
system("pause");
}