1843947 Members
2460 Online
110226 Solutions
New Discussion

Re: Read a binary file

 
Mokkarala Prakash
New Member

Read a binary file

Hi folks,

I need some help! I am trying to read a binary file in my HP-C program. Fopen
command does not distinguish between the binary and text files. So i have
decided to use a system command to tell HP that I am bringing in a binary file.
Is this the right way? If it is how do I convey my message using file command ?
Thanks.
4 REPLIES 4
Paul Hite_2
Frequent Advisor

Re: Read a binary file

Just use fopen. There is no way to inform the kernel that the file is an
"ascii file" or "binary file". The kernel doesn't care. It just opens the
file and delivers the bytes.
Mokkarala Prakash
New Member

Re: Read a binary file

I still can't get the value I am supposed to; This is what I am doing:

fp=fopen("bxr27700.12r","r");
fscanf(fp,"hu\n",&s);/* reading a unsigned short integer*/
printf("%hu\n",s);

I get a value 0;

Once this works, I will be swapping bytes to convert to big-endian ( from
little endian).
Thanks for the help so far!
Paul Hite_2
Frequent Advisor

Re: Read a binary file

fscanf is a function, which, as you have used it, is going to try to convert
ascii to binary. This would appropriate if you were reading a tty to load a
value in a binary number.

In your case, no conversion is needed. You just want 2 bytes to be read.
Change your second line to:

fread(&s, sizeof s, 1, fp);

This will read the first two bytes of your file and store them in s. Use "od
-d" on your input file to verify the result.
Mokkarala Prakash
New Member

Re: Read a binary file

Thanks Paul, it worked, at last. Your help is very much appreciated. Now, I can
have a good night's sleep.