[英]C language / How to read input from one file and write an output to another file
我在從一個文件讀取輸入並將輸出寫入另一個文件時遇到問題。
這是我的代碼
#include <stdio.h>
#include <math.h>
//Variables declarations
FILE *reportfile;
FILE *inputfile;
char ratioName[20];
char nameorganization[25];
int asset1,asset2,asset3;
int lia1,lia2,lia3;
float asset;
float liabilites;
float ratio;
int ave_asset;
int ave_liabilites;
float ave_ratio;
char year[5]
//char currentasset[15];
//char currentLia[30];
//char tekstRatio[45];
//void
void ReadingData(void);
void DoCalcs(void);
void Report(void);
int main(void) {
ReadingData();
DoCalcs();
Report();
return 0;
}
void ReadingData(void){
inputfile = fopen("c:\\class\\current.txt" , "r");
fgets(nameorganization,25, inputfile);
fscanf(inputfile,"%d%d\n", &asset1, &lia1);
fscanf(inputfile,"%d%d\n", &asset2, &lia2);
fscanf(inputfile,"%d%d", &asset3, &lia3);
fclose(inputfile);
}
void DoCalcs(void){
ratio = asset / liabilites;
ave_asset = (asset1 + asset2 + asset3) / 3;
ave_liabilites = (lia1 + lia2 + lia3) / 3;
ave_ratio = ratio / 3;
}
void Report(void){
reportfile = fopen("c:\\class\\alimbetm_cr.txt","w");
fprintf(reportfile,"\n");
fprintf(reportfile,"Current Ratio Report",ratioName);
fprintf(reportfile,"Year");
//fprintf(reportfile,"Current Asset",currentasset);
}
//void GettingInfo(void){
//printf("Please type ratio: ");
//scanf();
//}
當我運行它時,它將文件保存到新磁盤但刪除舊數據,這不是我想要的。 我想要的是從一個文件讀取輸入/數據並將機器人輸入/輸出寫入另一個文件而不刪除輸入。
這是輸入文件數據(current.txt)
Hi-Tech Leisure Products
47900 31007
34500 9100
57984 14822
這應該如何放在新文件上
Hi-Tech Leisure Products
Current Ratio Report
Current Current Current
Year Assets Liabilities Ratio
----------------------------------------------------------
2010 47900 31007 1.54
2011 34500 9100 3.79
2012 57984 14822 3.91
----------------------------------------------------------
Average 46795 18310 3.08
This report produced by Raul Jimenez.
請幫忙
在這種情況下,您需要使用"a"
而不是"w"
因為write
函數用於清除舊數據並寫入新數據
發布的代碼無法編譯! 第一個問題是這個語句:
char year[5]
缺少尾隨分號;
.
關於:
#include <math.h>
在發布的代碼中沒有使用math.h
任何“功能”。 包含那些內容未被使用的頭文件是一種非常糟糕的編程實踐。 建議刪除該語句。
關於:
reportfile = fopen("c:\\class\\alimbetm_cr.txt","w");
模式w
導致輸出文件被截斷為 0 長度。
由於您想保留輸出文件的舊內容並簡單地添加更多數據。 強烈建議使用;
reportfile = fopen("c:\\class\\alimbetm_cr.txt","a");
其中模式a
將以append
模式打開輸出文件,以便將新數據添加到現有文件的末尾。
當然,始終檢查reportfile
以確保它不是 NULL(即對fopen()
的調用成功。
請注意,此語句無法編譯:
fprintf(reportfile,"Current Ratio Report",ratioName);
因為它有一個參數但沒有匹配的“輸出格式轉換”說明符。 建議(在這種情況下)刪除參數: ratioName
對fopen()
和fclose()
的調用分散在整個代碼中。 由於當前正在寫入,因此只會從輸入文件中讀取一條記錄,並且只會將一條記錄寫入輸出文件。 當輸入文件包含多條記錄時,這將是一個主要問題。
“所需輸出”表示第一件事應該是:“高科技休閑產品”然后:“當前比率報告”但是,沒有語句(在Report()
)實際輸出第二個語句和字符數組ratioName[]
從未設置為任何特定值。
“所需輸出”表示 2 行列標題等,但沒有實際輸出這些列標題的代碼( year
除外)。 數據行、 Average:
行、 author
行也存在類似的考慮。 每行的每個數據都需要由代碼專門輸出,它們不會“神奇地”出現在輸出文件中。
關於;
ratio = asset / liabilites;
asset
和liabilites
均未設置為任何特定值,因此它們將(由於它們的聲明位置)包含值 0.0f。 所以這種划分將導致代碼的 DIVIDE BY ZERO 崩潰。
還有很多問題,但以上應該讓你朝着正確的方向開始。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.