簡體   English   中英

嘗試在 c 程序中讀取和寫入相同的代碼

[英]trying read and write on the same code in c program

幫助我正在嘗試將數據寫入文件中。 然后,試圖讀回它,但它不起作用。

#include <stdio.h>
    
int main(void) {
    FILE *fptr = fopen("try.txt", "r+");
    char line[1000];
    
    fprintf(fptr, "i have new number = 1425");
        
    while (fgets(line, 1000, fptr)) {
        printf("%s",line);
    }
    
    return 0;
}

您必須在讀寫操作之間使用定位 function 例如rewind()fseek()

請注意,流的更新模式非常混亂且容易出錯,您應該避免使用它並相應地構建您的程序。

順便說一句,如果try.txt不存在,您的程序將無法打開它,但您不檢查fopen失敗,因此在這種情況下您將獲得未定義的行為。

這是修改后的版本:

#include <stdio.h>
    
int main(void) {
    char line[1000];
    FILE *fptr = fopen("try.txt", "w+");
    
    if (fptr != NULL) {
        fprintf(fptr, "I have new number = 1425\n");
        
        rewind(fptr);
        while (fgets(line, sizeof line, fptr)) {
            printf("%s", line);
        }
        fclose(fptr);
    }
    return 0;
}

暫無
暫無

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

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