Home > Enterprise >  How to read binary data from file as string in C
How to read binary data from file as string in C

Time:09-30

I have a .dat file I am trying to read from that has binary data. I have tried using

FILE *fp=fopen("whatever.dat","rb");

unsigned char buf[BUFFER_SIZE];

while(fread(buf,sizeof(buf),1,fp)){
     printf("%s",buf);

}

to print the contents of the file, but it will only read the CSEP signature. After that, it stops reading. How do I get it to read the whole file?

CodePudding user response:

As @Barmar said, strings are null terminated. I prefer to use fwrite and get the file size, and output it to stdout. Since "get the file size" is dangerous, I suggest using sizeof(buf) instead.

FILE *fp = fopen("whatever.dat", "rb");

unsigned char buf[BUFFER_SIZE];

while(fread(buf, sizeof(buf), 1, fp)){
    fwrite(buf, sizeof(char), sizeof(buf), stdout);
        // Note, you can change "sizeof char" into 1.
}

CodePudding user response:

Read data into a buffer, noting the length of it that was used.

Then print that buffer with fwrite(), possible a portion of it.

Note many characters do not print text as they are control characters.

if (fp) {
  unsigned char buf[BUFFER_SIZE];
  size_t len; 
  while((len = fread(buf,sizeof buf, 1, fp)) > 0) {
    fwrite(buf,len, 1, stdout);
  }
  
  • Related