从 .au 文件中读取幻数

Read Magic Number from .au File

我写了一个小程序从 .au 文件中获取幻数并将其打印到控制台,但每次我尝试时,我都没有得到预期的 .snd,而是得到 .snd$相反。

我不确定为什么会这样,考虑到我只读取 4 个字节,这就是幻数的组成部分。那么,额外的字符来自哪里?

#include <stdio.H>

int main()
{
    FILE *fin;
    int r;
    char m[4], path[20];

    scanf("%s", path);
    fin = fopen(path, "r");
    r = fread(&m, sizeof(char), 4, fin);
    printf("magic number is %s\n", m);

    return 0;
}

您正在打印它,就好像它是一个字符串,这在 C 中意味着它以 NUL 结尾。像这样更改您的代码,它将按您预期的那样工作:

char m[5];
m[4] = '[=10=]';  /* add terminating NUL */

此外,您应该知道 scanf is a dangerous function。请改用命令行参数。

问题不在于你的阅读方式。 问题是你的变量只有4个字符长度,需要一个空字符来表示结束。

带 %s 的 printf 将打印变量的内容,直到到达空字符,直到它可以打印垃圾,如果你的变量没有正确结束。 要解决这个问题,您可以使用更大的变量并将 [4] 字符设置为 null。

新代码应该是什么样子:

#include <stdio.H>

int main()
{
    FILE *fin;
    int r;
    char m[5], path[20];

    scanf("%s", path); 
    /*Scanf can be dangerous because it can cause buffer overflow, 
    it means that you can fill your variable with more bytes than it supports, which can end up being used for buffer overflow attacks:                     
    See more: http://en.wikipedia.org/wiki/Buffer_overflow */
    fin = fopen(path, "r");
    r = fread(&m, sizeof(char), 4, fin);
    m[4] = '[=10=]';

    printf("magic number is %s\n", m);

    return 0;
}