如何在C中检查文件是文本(ASCII)还是二进制 [英] How can I check if file is text (ASCII) or binary in C

查看:144
本文介绍了如何在C中检查文件是文本(ASCII)还是二进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to write C code that checks to see if a file is text(ASCII) or Binary

有人可以帮忙吗? 谢谢

Could someone help? Thanks

推荐答案

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

Typical method is to read the first several hundred bytes and look for ASCII NUL.

如果文件包含NUL,则绝对是二进制文件.大多数二进制文件的确包含NUL字节,但是文本文件绝对不能包含NUL字节.

If the file contains NUL, it is definitely a binary file. Most binary files do contain NUL bytes, but text files should never contain NUL bytes.

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

请注意,这是一种启发式方法.换句话说,有时候是错误的.

Be warned that this is a heuristic. In other words, it will be wrong sometimes.

这篇关于如何在C中检查文件是文本(ASCII)还是二进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆