How can I check if file is text (ASCII) or binary in C

牧云@^-^@ 提交于 2020-01-03 09:28:06

问题


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

Could someone help? Thanks


回答1:


Typical method is to read the first several hundred bytes and look for ASCII 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.




回答2:


Read all characters and see if all of them are ASCII, that is, with codes from 0 to 127 inclusive.

Some tools determine whether a file is a text file or a binary file by just checking whether or not it has any byte with code 0.

Clearly, if you apply both of these methods, you will get different results for some files, so, you have to define what it is exactly that you're looking for.



来源:https://stackoverflow.com/questions/14618008/how-can-i-check-if-file-is-text-ascii-or-binary-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!