Reading a binary file in text or ASCII format

Hi All,
Please suggest me how to read a binary file in text or ASCII format.

thanks
Nagendra

Nagendra,

There is no way to convert binary file to ascii format.These two are basic intrinsic file properties. meaning during creation itself you determine if the file has to be binary or ascii text. Binary file will be usually of some specified format say pdf/executable/word document etc. for converting to text you will have specific tools for specific formats to ascii/text etc.

But if you binary file contains some valid ASCII strings in it, say like error messages you can filter them using strings command.

strings binaryFileName

hope it helps.

rishi :smiley:

This comes up all too often. Windows has text files. Unix does not. Unix is not Windows. In Unix a file is a file is a file. It's a bag of bytes. Period.

Because a standard C string uses ASCII zero (nul character) as the end of string, that data from files that contain nuls (in Windows these are binary files, in Unix they are just files) cannot be parsed as strings because the nuls confuse everything.

To the OP: try

od -c filename

to find out what is in the file. Then you will know if you can read it using standard string C calls like fgets(). Or if you will have to use fread().

After you've programmed for a while you tend to bypass fread and fgets, especially when you're dealing with large files that may contain interesting stuff.
This reads an entire file containing anything into a buffer:


#include <stddef.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/stat.h>
#include <errno.h>
#include <assert.h>

#define ck(x) \
if( (x) == (-1) ){ perror("");exit(EXIT_FAILURE);}

/* read a buffer from a file */
ssize_t readall(int fd, void *buf, size_t *bytes){
     ssize_t nread = 0, n=0;
     size_t nbyte = *bytes;

     do {
         if ((n = read(fd, &((char *)buf)[nread], nbyte - nread)) == -1) {
             if (errno == EINTR)
                 continue;
             else
                 return (-1);
         }
         if (n == 0)
             return nread;
         nread += n;
     } while (nread < nbyte);
     return nread;
}

/* read control */
void readfile(char *fname, char *buffer, size_t *size, mode_t *mode)
{
   int fd=0;   
   struct stat st;
   
   ck(fd=open(fname,O_RDONLY) );
   ck(fstat(fd,&st) );
   *size=st.st_size;   
   *mode=st.st_mode;
   buffer=calloc(1,*size+1);
   ck(readall(fd, buffer, size) );    
   ck(close(fd) );
}


int main(int argc, char *argv[])
{
   char *buffer=NULL;
   size_t size;
   mode_t mode;
 
   readfile(argv[1],buffer,&size,&mode);
   /* play with buffer here  */
   free(buffer);
   return 0;  
}

1 Like

hi i am trying to read a binary file [.dat]. its in linux, i want that file to work in windows. but in windows i cannot read this file. could someone help me to read the dat file.