简体   繁体   English

与inttypes.h,fscanf(),fprintf()不一致

[英]Inconsistency with inttypes.h, fscanf(), fprintf()

I'm having some problems with inttypes, illustrated here by this tiny code sample: 我在使用inttypes时遇到了一些问题,此小代码示例对此进行了说明:

#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>


void print_byte(uint8_t b)
{
    printf("%d%d%d%d%d%d%d%d\n",
        !!(b & 128), !!(b & 64), !!(b & 32), !!(b & 16),
        !!(b & 8), !!(b & 4), !!(b & 2), !!(b & 1));
}

int main()
{
    FILE *f;
    uint8_t bs = 8;
    uint16_t bw = 100, bh = 200;
    f = fopen("out", "w+");

    print_byte(bs);
    printf("%"PRIu8" %"PRIu16" %"PRIu16"\n", bs, bw, bh);
    fprintf(f, "%"PRIu8"%"PRIu16"%"PRIu16, bs, bw, bh);
    fclose(f);

    f = fopen("out", "r");

    fscanf(f, "%"SCNu8"%"SCNu16"%"SCNu16, &bs, &bw, &bh);   
    printf("%"PRIu8" %"PRIu16" %"PRIu16"\n", bs, bw, bh);
    print_byte(bs);
    fclose(f);

    return 0;
}

Gives me 给我

gcc -o test test.c && ./test
00001000
8 100 200
104 100 200
01101000

If I change the SCNu8 to SCNo8 in the fscanf, I get what I'm supposed to get: 如果我在fscanf SCNu8 SCNo8更改为SCNu8 ,我将得到:

00001000
8 100 200
8 100 200
00001000

Where is the problem? 问题出在哪儿? I don't see why it doesn't work for the first code, but works when I interpret that byte as an octal value. 我不明白为什么它不适用于第一个代码,但是当我将该字节解释为八进制值时起作用。

The problem is that the values in your text file end up being merged together, like this: 问题是文本文件中的值最终合并在一起,如下所示:

8100200

That is why you cannot read the data back correctly: fscanf does not know where the first number ends and the next number starts. 这就是为什么您无法正确读回数据的原因: fscanf不知道第一个数字在哪里结束,而下一个数字在哪里开始。

Putting spaces into the fprintf format line fixes this problem: 将空格放入fprintf格式行可解决此问题:

fprintf(f, "%"PRIu8" %"PRIu16" %"PRIu16, bs, bw, bh);

[ fscanf is] supposed to read a 1 byte value then two 2 bytes [ fscanf应该]读取一个1字节的值,然后读取两个2字节

fscanf reads text, not bytes. fscanf读取文本,而不读取字节。 If you would like to write bytes, use library functions for binary output and input, ie fwrite and fread : 如果您想写字节,请使用库函数进行二进制输出和输入,即fwritefread

// Writing in binary
f = fopen("out.bin", "wb");
fwrite(&bs, sizeof(bs), 1, f);
fwrite(&bw, sizeof(bw), 1, f);
fwrite(&bh, sizeof(bh), 1, f);
fclose(f);
// Reading in binary
f = fopen("out.bin", "rb");
fread(&bs, sizeof(bs), 1, f);
fread(&bw, sizeof(bw), 1, f);
fread(&bh, sizeof(bh), 1, f);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM