Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

ascii

binary

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

Could someone help? Thanks

like image 553
user1684072 Avatar asked Jan 31 '13 03:01

user1684072


People also ask

How can you tell if a file is ASCII or binary?

You can use file --mime-encoding | grep binary to detect if a file is a binary file.

Is a text file binary or ASCII?

A text file is the one in which data is stored in the form of ASCII characters and is normally used for storing a stream of characters.

How do I identify an ASCII file?

If a file contains only the decimal bytes 9–13, 32–126, it's probably a pure ASCII text file. Otherwise, it's not. However, it may still be text in another encoding.

What is text file and binary file in C?

In text file, text, character, numbers are stored one character per byte i.e. 32667 occupies 5 bytes even though it occupies 2 bytes in memory. In binary file data is stored in binary format and each data would occupy the same number of bytes on disks as it occupies in memory.


2 Answers

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.

like image 131
Dietrich Epp Avatar answered Oct 13 '22 14:10

Dietrich Epp


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.

like image 22
Alexey Frunze Avatar answered Oct 13 '22 13:10

Alexey Frunze