[英]Writing a sequence of numbers to a file in C
我是編程新手。 我已經編寫了一個程序來對數字進行某種操作,現在我要做的就是從文件中讀取這些數字並將它們寫入另一個文件中。 我正在使用此代碼:char number [20]; 整數值,選擇,結果;
{
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;
但它只會寫入序列中的最后一個數字。 如果有人可以告訴我我做錯了,我將不勝感激。 謝謝瑪麗亞
首先嘗試在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.