如何检查文件是 C 中的文本 (ASCII) 还是二进制



我需要编写 C 代码来检查文件是文本 (ASCII) 还是二进制

有人可以帮忙吗?谢谢

典型的方法是读取前几百个字节并查找 ASCII NUL。

如果文件包含 NUL,则它绝对是二进制文件。 大多数二进制文件确实包含 NUL 字节,但文本文件不应包含 NUL 字节。

#include <string.h>
bool is_binary(const void *data, size_t len)
{
    return memchr(data, '', len) != NULL;
}

请注意,这是一种启发式方法。 换句话说,有时它会出错。

读取所有字符,查看它们是否都是 ASCII,即包含 0 到 127 的代码。

某些工具只需检查文件是否有代码为 0 的字节即可确定文件是文本文件还是二进制文件。

显然,如果您同时应用这两种方法,则会为某些文件获得不同的结果,因此,您必须定义要查找的确切内容。

你可以使用libmagic。 下面的代码将大致向您展示"file"命令的执行方式。 (下面的代码又快又脏——可能需要清理。

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

//------------------------------------------------------------------------------
struct magic_set * prep_magic(int flags)
{
struct magic_set *magic = magic_open(flags);
const char *errstring;
int action = 0;
const char *magicfile = NULL;
if (magicfile == NULL)
    magicfile = magic_getpath(magicfile, action);
if (magic == NULL)
    {
        printf("Can't create magic");
        return NULL;
    }
if (magic_load(magic, magicfile) == -1)
    {
        printf("%s", magic_error(magic));
        magic_close(magic);
        return NULL;
    }
if ((errstring = magic_error(magic)) != NULL)
        printf("%sn", errstring);
return magic;
/* END FUNCTION prep_magic */ }
//------------------------------------------------------------------------------
int main(int argc, char **argv)
{
int flags = 0;
struct magic_set *msetptr = NULL;
const char *testfile = (char *)"/etc/motd";

msetptr = prep_magic(flags);
if( msetptr == NULL )
    printf("no mset ptrn");
const char *typer;
typer = magic_file( msetptr, testfile );
printf("typer = %sn", typer );
return 0;
/* END PROGRAM */ }

最新更新