Search code examples
cfile-iognu

C Opening a file to check if it is Binary, if so print it is binary


I've made a program that opens files and searches for a word

I want it to only work on TEXT Files

Is there a way provided by C to check if a file is BINARY, and if so, I want to exit the program before any operations take place

Thanks


Solution

  • No, there isn't, because it's impossible to tell for sure. If you expect a specific encoding, you can check yourself whether the file contents are valid in this encoding, e.g. if you expect ASCII, all bytes must be <= 0x7f. If you expect UTF-8, it's a bit more complicated, see a description of it.

    In any case, there's no guarantee that a "binary" file would not by accident look like a valid file in any given text encoding. In fact, the term "binary file" doesn't make too much sense, as all files contain binary data.