[英]Writing a sequence of numbers to a file in C
I am new to programming. 我是编程新手。 I have written a program that performs a certain operation with numbers, all I need to do now is to read those numbers from a file and to write them into a different file.
我已经编写了一个程序来对数字进行某种操作,现在我要做的就是从文件中读取这些数字并将它们写入另一个文件中。 I am using this code: char number[20];
我正在使用此代码:char number [20]; int value, choice, result;
整数值,选择,结果;
{
FILE *file_in;
file_in = fopen("roman.txt", "r");
while (!feof(file_in))
{
fscanf(file_in, "%s", number);
fclose(file_in);
FILE *file_out;
result = RomantoArabic(number, value);
file_out = fopen("arabic.txt", "a");
fprintf(file_out, "%d\n", result);
fclose(file_out);
}
return 0;
but it only writes the last number from the sequence. 但它只会写入序列中的最后一个数字。 I'd be very grateful if someone could tell me what I am doing wrong.
如果有人可以告诉我我做错了,我将不胜感激。 thanks maria
谢谢玛丽亚
first try to open the file outside the while loop and run it again and close the files after the loop. 首先尝试在while循环外打开文件,然后再次运行并在循环后关闭文件。
{
FILE *file_in;
File *file_out;
file_in = fopen("roman.txt", "r");
if (file_in == NULL) {
printf("Error: unable to open "roman.txt.\n");
exit(EXIT_FAILURE);
}
file_out = fopen("arabic.txt", "a");
if (file_out == NULL) {
printf("Error: unable to open ‘arabic.txt’\n");
exit(EXIT_FAILURE);
}
while (!feof(file_in))
{
fscanf(file_in, "%s", number);
result = RomantoArabic(number, value);
fprintf(file_out, "%d\n", result);
}
fclose(file_in);
fclose(file_out);
return 0;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.