2012-03-14 58 views
-2

我正在寫一個程序的自動取款機。我.txt文件是一個賬戶餘額(在這種情況下,1500.00)。如何在.txt文件讀取,編輯帳戶餘額,然後將其保存到文件?如何在C中讀取和編輯.txt文件?

例如,如果我要求用戶輸入一筆金額爲300.00的存款,我希望能夠將300.00添加到文件中現有的1500.00,然後覆蓋1500.00,總金額爲1800.00。

這是我到目前爲止。

float deposit; 
    float var; 

printf("Current account balance:"); 
if ((file_account = fopen ("account.txt", "r")) == NULL) 
{ 
    printf ("Error finding account balance.\n"); 
    return; 
} 

while ((fscanf (file_account, "%c", &var)) != EOF) 
{ 
    printf ("%c", var); 
} 
printf ("\n"); 
fclose (file_account); 

for (deposit=0; deposit>0; deposit++) 
{ 
    if (deposit > 0) 
    { 
     printf ("Enter amount to deposit:"); 
     scanf ("%f", &deposit); 
     //file_account + deposit; 
     fprintf (file_account, "Your new account balance is: %f", deposit); 
    } 
    else 
    { 
     printf ("Amount must be 0 or more."); 
    } 
    fclose (file_account); 

}

+4

有什麼你到目前爲止嘗試過?你研究了什麼?我沒有看到這方面的努力。 – 2012-03-14 19:13:05

+1

如果這是家庭作業,請將其標記爲[功課。如果不是,... – 2012-03-14 19:18:38

+0

對不起,我是新手! – user1269888 2012-03-14 19:21:15

回答

1

你需要幾個步驟在這裏:

int triedCreating = 0; 

OPEN: 
FILE *filePtr = fopen("test.txt", "r+"); 

if (!filePtr) 
{ 
    // try to create the file 
    if (!triedCreating) 
    { 
     triedCreating = 1; 
     fclose(fopen("test.txt", "w")); 
     goto OPEN; 
    } 
    fprintf(stderr, "Error opening file %i. Message: %s", errno, strerror(errno)); 
    exit(EXIT_FAILURE); 
} 

// scan for the float 
float value = 0.0f; 
fscanf(filePtr, "%f", &value); 

printf("current value: %f\nvalue to add: ", value); 

// add the new value 
float add = 0.0f; 
scanf("%f", &add); 

value += add; 

// write the new value 
fseek(filePtr, 0, SEEK_SET); 

fprintf(filePtr, "%f", value); 

fclose(filePtr); 

您可能希望有不同的格式爲您printf()的,這樣當讀取到一個普通的文本編輯器,它看起來更好。

+0

我定義我的文件指針在main(file_account)。這是我打來的功能。我會多玩幾次。感謝您的幫助!對此,我真的非常感激。 – user1269888 2012-03-14 19:37:20

+0

@ user1269888沒問題!只要確定接受答案:) – 2012-03-14 19:38:46

0

你應該用一個文件指針,打開&讀取該文件,修改內容根據您的意願和寫回文件。

例如:

File *fp; // creates a pointer to a file 
fp = fopen(filename,"r+"); //opens file with read-write permissions 
if(fp!=NULL) { 
    fscanf(fp,"%d",&var);  //read contents of file 
} 

fprintf(fp,"%d",var);   //write contents to file 
fclose(fp);     //close the file after you are done 
+0

'rw'不是一個有效的fopen說明符。你可能想要'r +'或'w +'。 – 2012-03-14 19:28:25

+0

對不起,沒有意識到 – Chaos 2012-03-14 19:29:40

0

你可以閱讀和編輯文件,基本的文件的幫助I/O(輸入/輸出)在C I例如像一個簡單的方式功能,寫入文件如果它存在,並且如果不創建名稱的文件,然後寫入它。

基礎教程可以在 http://www.tutorialspoint.com/cprogramming/c_file_io.htm

現在發現,如果你談論的是有很多的在它的內容複雜的.txt文件,然後你需要找到一個特定的詞,並改變它,我覺得在Linux中你可以調用腳本來讀取文件,使用SED進行編輯(用於過濾和轉換文本的流編輯器),這在Linux中有點困難。您可以在下面的鏈接找到它的教程 http://www.panix.com/~elflord/unix/sed.html