簡體   English   中英

將結構寫入 C 中的文件時出現令人困惑的錯誤

[英]Confusing error when writing structure to file in C

我正在嘗試將結構寫入 dat 文件,一切正常,但 dat 文件中的數據變成隨機字符(在其他格式(如 txt)中相同)

#include <stdio.h>
#include <string.h>

struct Product
{
    char ProId[20];
    char ProName[30];
    float Price;
    int Quantity;
    int CatId;
    
};

int main(){
    FILE *f;
    f = fopen ("Product.dat", "w+");
    if (f == NULL)
    {
        fprintf(stderr, "\nError opened file\n");
    }
                
    Product p1;
    strcpy(p1.ProId, "1");
    strcpy(p1.ProName, "Candy");
    p1.Price = 4.5;
    p1.Quantity = 5;
    p1.CatId = 1;
    
    fwrite(&p1, sizeof(p1), 1, f);
    fclose(f);
    
    return(0);
}

Product.dat 中的數據:

1 u            ÿÿÿÿCandy              Ù$@           @      

我嘗試搜索此錯誤但無濟於事。 請幫助我,有什么問題? 謝謝你。

我在我的 WSL2 上編譯並運行了你的代碼,遇到了同樣的問題,這里是 hexdump: 你的代碼

對於字符串“Candy”,如果確實在這個結構中復制,我認為原因是這個結構是在堆棧上分配的,所以它被一些垃圾數據污染了。 所以我在聲明這個結構之后進行了清理,它影響了: 我的代碼

這是我修改的代碼,注意 memset():

#include <stdio.h>
#include <string.h>

struct Product
{
        char ProId[20];
        char ProName[30];
        float Price;
        int Quantity;
        int CatId;

};

int main(){
        FILE *f;
        f = fopen ("Product.dat", "w+");
        if (f == NULL)
        {
                fprintf(stderr, "\nError opened file\n");
        }

        struct Product p1;
        memset(&p1, 0, sizeof(p1));
        strcpy(p1.ProId, "1");
        strcpy(p1.ProName, "Candy");
        p1.Price = 4.5;
        p1.Quantity = 5;
        p1.CatId = 1;

        fwrite(&p1, sizeof(p1), 1, f);
        fclose(f);

        return(0);
}

暫無
暫無

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

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