我可以在c语言中使用fscanf和二进制文件吗?

时间:2015-02-13 18:47:07

标签: c binaryfiles scanf

所以我参加了考试,其中一个例子包括扫描二进制文件中的名字。我曾使用fscanf(),但我的教授告诉我,我不能在二进制文件中使用fscanf。但为什么?即使我这样做,我的程序也能正常工作。

1 个答案:

答案 0 :(得分:1)

我承认我没有找到解释fscanf()和二进制文件错误的方法,但这里有一个例子,说明如何生成binary文件错误地fscanf()

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

struct Entry
{
    char text[64];
    int  age;
};

int main()
{
    FILE        *file;
    struct Entry entry;

    file = fopen("data.bin", "wb");
    if (file == NULL)
        return -1;

    entry.age = 30;

    memset(entry.text, 0, sizeof(entry.text));
    strcpy(entry.text, "Iharob Al Asimi");

    fwrite(&entry, sizeof(entry), 1, file);

    entry.age = 22;

    memset(entry.text, 0, sizeof(entry.text));
    strcpy(entry.text, "Claudio Urdaneta");

    fwrite(&entry, sizeof(entry), 1, file);

    entry.age = 29;

    memset(entry.text, 0, sizeof(entry.text));
    strcpy(entry.text, "Dayana Orozco");

    fwrite(&entry, sizeof(entry), 1, file);
    fclose(file);

    file = fopen("data.bin", "rb");
    if (file == NULL)
        return -1;
    fprintf(stderr, "with fscanf()\n");
    /* this is intentionally == 1 to prove the point */
    while (fscanf(file, "%63s%d", entry.text, &entry.age) == 1)
        fprintf(stderr, "\t%s, %d\n", entry.text, entry.age);

    rewind(file);

    fprintf(stderr, "with fscanf()\n");
    while (fread(&entry, sizeof(entry), 1, file) == 1)
        fprintf(stderr, "\t%s, %d\n", entry.text, entry.age);

    fclose(file);

    return 0;
}

问题是fscanf()将扫描文本并与您传递给它的说明符匹配。

但是二进制文件只是存储在给定结构中的一堆字节,在上面的例子中我们每条记录写64 + sizeof(int)个字节,其中一个项只是文本所以用fscanf()读取字节按预期工作,它当然会停留在空白角色。

但是该数字在文件中没有文本重新表示,因此您无法使用fscanf()阅读它。

另外,请注意这个

while (fscanf(file, "%63s%d", entry.text, &entry.age) == 1)

正确的做法是

while (fscanf(file, "%63s%d", entry.text, &entry.age) == 2)

但是不会打印任何内容,因为整数不匹配。

因此,在使用二进制文件时,您需要

  • fread() / fwrite()

而数据只是文本

  • fprintf() / fscanf()

会很好。

相关问题