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

2019-06-23 02:24发布

问题:

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.



标签: c binary ascii