簡體   English   中英

fwrite() 和 fread() 在 C XCODE 中不起作用

[英]fwrite() and fread() don't work in C XCODE

我注意到 fread() 和 fwrite() 在我的程序中不起作用。 我寫了這個小程序來演示它。

#include <stdio.h>

typedef struct Product {
    float size;
    float price;
} Product;

int main() {
    Product my_prod;
    my_prod.price = 13.2;
    my_prod.size = 10.3;

    FILE* file_in = fopen("/Users/piton/Desktop/UniverProg/Test/Test/input.txt", "w");
    if (file_in == NULL)
        printf("ERROR");

    fwrite(&my_prod, sizeof(Product), 1, file_in);
    
    fclose(file_in);
    return 0;
}

所以,我在 input.txt 中有輸出:ÕÃ$A33SA

(是的,我將文件命名為“輸入”,但實際上它是用於輸出的)

請幫忙

謝謝

即使您暗示您的文件是文本文件 (input.txt),使用“fwrite”函數和包含浮點變量的結構的輸出將使用存儲浮點值所需的字節數輸出數據以二進制方式。 對於大多數 C 程序來說,這將是四個字節。 因此,使用您的程序,我運行該程序,然后使用十六進制文件查看器查看原始十六進制數據。 這是我看到的。

CD CC 24 41  33 33 53 41

這八個字節與存儲的兩個十進制數的長度一致。 “CD CC 24 41”表示值“13.2”,“33 33 53 41”表示值“10.3”。 為了驗證這一點,我在您的程序中添加了幾行代碼,以便程序從文件中讀回數據並打印出存儲在該文件中的值。

#include <stdio.h>

typedef struct Product
{
    float size;
    float price;
} Product;

int main()
{
    Product my_prod;
    my_prod.price = 13.2;
    my_prod.size = 10.3;
    
    FILE* file_out = fopen("input.txt", "w"); /* I changed the name to file.out */
    if (file_out == NULL)
        printf("ERROR");
    
    fwrite(&my_prod, sizeof(Product), 1, file_out);
    
    fclose(file_out);
    
    FILE* file_in = fopen("input.txt", "r"); /* I then reopened the file to read */
    fread(&my_prod, sizeof(struct Product), 1, file_in);
    
    printf("Price: %f, Size: %f\n", my_prod.price, my_prod.size);
    
    fclose(file_in);
    
    return 0;
}
 

當我運行程序時,這是從文件中讀取的數據的輸出。

Price: 13.200000, Size: 10.300000

所以數據最初是正確存儲的。

如評論中所述,由於數據以二進制方式存儲,您可能希望將文件作為二進制文件打開(例如 fopen("input.txt", "wb"))。

我希望這能澄清事情。

問候。

暫無
暫無

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

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