Thursday, Nov 21st

Last update12:59:40 PM GMT

How to check if a file is a binary file or an ascii file?

Write e-mail

Here is a sample C program, which checks the bytes in the file to see if they are ASCII or not

#include <stdio.h>

int main(int argc, char *argv[])
{
 unsigned char ch;
 FILE *file;
 int binaryFile = FALSE;

 file = fopen(<FILE_PATH>, "rb");            // Open in Binary mode for the first time.


 while((fread(&ch, 1, 1, file) == 1) && (binaryFile == FALSE))
 {
 if(ch < 9 || ch == 11 || (ch > 13 && ch < 32) || ch == 255)
 {
 binaryFile = 1;                  
 }
 }

 fclose(file);   

 if(binaryFile)
 file = fopen(<FILE_PATH>, "rb");   
 else                                  
 file = fopen(<FILE_PATH>, "r");


 if(binaryFile)
 {
 while(fread(&ch, 1, 1, file) == 1)  
 {
 // Do whatever you want here with the binary file byte...
 }
 }
 else                               
 {
 while(fread(&ch, 1, 1, file) == 1) 
 {
 // This is ASCII data, can easily print it!
 putchar(ch);          
 }
 }

 fclose(file);

 return(0); 
}
argaiv1827

Share this post



Web Hosting