c - 读取包含奇数字符的 DAT 文件

标签 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]

最佳答案

You'll most likely want a structure that matches that format and then you read the data into it.

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

    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);

关于c - 读取包含奇数字符的 DAT 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40951975/

相关文章:

c - 文件无法识别 : File format not recognized error in C

C 指向数组/指针数组的指针消歧

c - Printf 输出顺序相反

c - 左移计数 >= C 宏中类型的宽度

c - 在 C 中处理文本文件的异常行为

c - 如何创建一个数组,在一个维度上是动态的,而在其他维度上是静态的? C

c - 使用引用调用时,main 中动态分配的 char 指针不返回字符串

c - 为什么当我启动 make 时找不到 libSDL draw.[so/a]?

c - strlen 对于两字节字符串显示 0

C为不同的字符串获取相等的哈希值openssl