簡體   English   中英

在 C 的文本文件中修改 integer 值

[英]Modify an integer value in a textfile in C

假設我有一個這樣的文本文件:

106
60
107
50
108
37

所以 106 107 和 108 是我的 ID,而 60、50 和 37 是庫存數量。 我想修改庫存數量,比如我在 ID:106 上再增加 30 個,所以應該是 60+30=90。 所以我的問題是,我應該如何對其進行編碼以便更新文本文件。

我已經嘗試將文件掃描到數組中,但似乎沒有將數據掃描到數組中:

while(fscanf(filename, "%d", array[i]))
{
    i++;
}

我嘗試了這種方法,但它似乎不起作用。 這個問題有其他選擇嗎?

您不能輕易地修改文本文件,因為隨着數字增長到更多位數,您可能需要插入字節。

您應該使用循環來讀取文件並將更新的內容寫入新文件:

int update_file(FILE *in, FILE *out, int ref, int delta) {
    int id, quantity;
    int res = 0;

    while (fscanf(in, "%d%d", &id, &quantity) == 2) {
        if (id == ref) {
            quantity += delta;
            res++;
        }
        fprintf(out, "%d\n%d\n", id, quantity);
    }
    return res;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM