读取带有奇数字符的DAT文件

时间:2016-12-03 20:06:28

标签: c

我正在尝试读取和打印C中的dat文件的内容。我还在学习如何读取二进制文件,我认为读取文件的正确方法是逐字节的(如下所示)代码段:

unsigned char buffer;
FILE *fp;
fp = fopen("products.dat", "rb");

while (!feof(fp)) {
    fread(&buffer, 1, 1, fp);
    printf("%c", buffer);
}

这是我收到的输出:

    16010719-5109ABSORB leathercare setq�8�q�Њq�e����(\�@16011030-0456ANNO INEZ panel curtain�8�q�Њq�eH
ףp=
@16020623-8644ALVE deskpanel curtain�8�q�Њq�eq�Q��k!@16021117-5765ALVE add-on-unit for secretaryЊq�e\�(\���@16071127-9620ANTONIUS height adjustable clothes dryerЊq�e�
ףp=
@16080205-0344BEDDINGE seriesadjustable clothes dryerЊq�e�)\���(@16090505-4102ANDY drawer unit on casterslothes dryerЊq�e[\���(\@16100207-7038BEATA collectionon casterslothes dryerЊq�e��z�G��?16140311-3192BILLY systemionon casterslothes dryerЊq�e�\���(\!@16140312-0502ALVE laptop tablen casterslothes dryerЊq�e�H�z�G@16150309-1686AKURUM wall top cabinet framethes dryerЊq�e1�p=
ף@16150613-8211BEHANDLA seriescabinet framethes dryerЊq�e1)\���("@16150701-5897ANTONIUS shelfcabinet framethes dryerЊq�e��Q��@16150807-2103ANEBODA seriescabinet framethes dryerЊq�e���Q�� @16171215-4812ANTONIUS drying racket framethes dryerЊq�e�=
ףp=@16190603-3731ABSORB leathercleanert framethes dryerЊq�e���(\��#@16200211-9747BEATA ORKIDE duvet cover and pillowcase(s)Њq�e�������@16220729-5714ADMETE RUND chair pader and pillowcase(s)Њq�e_
ףp=
�?16240510-6077ANTIFONI floor/reading lamp pillowcase(s)Њq�es{�G�z@16270718-1760ALG mirroroor/reading lamp pillowcase(s)Њq�e�fffff� @@

我应该能够从这个文件中获取产品信息:产品代码,名称,数量和价格。我的阅读此文件的代码是否错误?

这是products.dat文件的内容 1]

1 个答案:

答案 0 :(得分:0)

  

您很可能想要一个与该格式匹配的结构   你把数据读进去了。

你应该遵循退休忍者的好建议。首先:

    struct product { char code[15], name[51];
                     short quant;
                     double price;
                   } buffer;
    while (fread(&buffer, sizeof buffer, 1, fp))
        printf("%s\t%-51s%3d %.2f\n", buffer.code, buffer.name,
                                      buffer.quant, buffer.price);