473,841 Members | 1,825 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

binary file reading in C

2 New Member
Hello all,

I'm trying to read in a binary file in C. I have the specification of the file format and everything. I can parse the file with a software called "010 Editor". This way I can check if the values I read in in my C program are correct.

The problem I have is parsing 32 bit integer values in C.

This is the pretty simple code:
Expand|Select|Wrap|Line Numbers
  1.     int temp = 0;
  2.     fread(&temp,sizeof(int),1,fp);
  3.     printf("%i\t",temp);
It works fine for most of the values in the file. But for some values in the file it is just not printing out the correct integer value.

E.g. :
binary file hex values: 8A 1A 32 01
integer value I get in C: 138
It should be : 20060810

-> 138 is the unsigned byte value of 8A. Am I just reading in 8A?

For the following example it works:
binary file hex values: E1 7A 7F 00
integer value I get in C: 8354529
It should be : 8354529

I also tried to read in the data bytewise from the file and combinig it to an integer by shifting bytewise.

Expand|Select|Wrap|Line Numbers
  1.     int temp = 0;
  2.     temp  = getc(fp);
  3.     temp |= getc(fp) << 8;
  4.     temp |= getc(fp) << 16;
  5.     temp |= getc(fp) << 24;
  6.     printf("%i\t",temp);
The results are the same...

I'm using the MS Visual Studio compiler on Windows.
I'm stuck with this problem for quite a while now and I would appreciate any help I can get.

Thank You!
Sep 15 '06 #1
4 29336
9,065 Recognized Expert Moderator Expert
Have you opened the file in binary mode (add a b to the end of the mode string) because

0x1A = 26 = ASCII Ctrl-Z

which is often(well used to be) used to indicate the end of a text file so the read could be stopping because it thinks it has reached the end of file if you have opened the file in text mode.
Sep 15 '06 #2
2 New Member
Thank you very much!

I think that solved my problem. I never thought about this..
I just added that "b" and everything seems to work now.

I also have to read in 24 bit and 8 bit integers.
I thought this piece of code should do the trick:

Expand|Select|Wrap|Line Numbers
  1. int read_int24(FILE *fp)
  2. {
  3.     int temp = 0;
  4.     temp  = (int)getc(fp);
  5.     temp |= (int)getc(fp) << 8;
  6.     temp |= (int)getc(fp) << 16;
  8.     return temp;
  9. }
  11. int read_int8(FILE *fp)
  12. {
  13.     int temp = (int)getc(fp);
  14.     return temp;
  15. }
It turns out that I'm just reading in 255 or 0 for 8 bit integers. I'm also not sure about the 24 bit integer values.
Do you have an idea what I'm doing wrong here? I think it's somthing with those byte-shifting operators I don't understand... :(
Maybe there is also an easier way to do this?

Thanks again, you are a great help!
Sep 18 '06 #3
9,065 Recognized Expert Moderator Expert
That code looks correct to me. The only possibility I can think of is that you have got to the end of the file. At the end of the file getc returns EOF and that often has a value -1 (all bits set), but that doesn't explain the 0's.

I would be stepping through the code with a symbolic debugger at this point.
Sep 18 '06 #4
Zebi Ben
1 New Member
I have a problem in reading binary files plz help
i have used fread function to read in binary files
Expand|Select|Wrap|Line Numbers
  1. Header *head;//structure holding 
  2. if ((fp = fopen("abc.bin", "rb+")) == NULL) return -1;
  3.     bytes_read=fread((char *)head, sizeof(Header ),1, fp);
  4.     //bytes_read = fread(buf, sizeof(buf), 1, fp);
  5.     if ( bytes_read ) {
  6.                 printf( "Number of characters has been read = %i\n", bytes_read );
  7.         printf( "buffer = %s\n", head);}
But this code reads only 1st byte
I want to read the entire file .. How can i do tht.. plz help...Also how can i get the values from binary file in the structure variable
Jul 18 '07 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

by: sredd01 | last post by:
Hello, Please look the code below where I am reading the first 2,2,4 bytes from a binary file using two methods. I am getting a wierd (wrong) output with ifstream and memcpy method, but get the correct output with CFile read. I am trying to get the values 1400 1050 and 2014 from the binary file. Can anybody point out the mistake in the following code?
by: Arnold | last post by:
I need to read a binary file and store it into a buffer in memory (system has large amount of RAM, 2GB+) then pass it to a function. The function accepts input as 32 bit unsigned longs (DWORD). I can pass a max of 512 words to it at a time. So I would pass them in chunks of 512 words until the whole file has been processed. I haven't worked with binary files before so I'm confused with how to store the binary file into memory. What sort of...
by: Patrick De Ridder | last post by:
Writing and subsequently reading an int repeatedly to and from a binary file I get an error when the int vanlue becomes >= 128. Is there a possible explanation for this? Patrick.
by: PJ Olson | last post by:
All, is there a speed or efficiency difference in using FileStream.Position vs. FileStream.Seek to navigate through a file?
by: John Dann | last post by:
I'm trying to read some binary data from a file created by another program. I know the binary file format but can't change or control the format. The binary data is organised such that it should populate a series of structures of specified variable composition. I have the structures created OK, but actually reading the files is giving me an error. Can I ask a simple question to start with: I'm trying to read the file using the...
by: Jack | last post by:
Hi I am having a little trouble trying to read a binary file, I would like to write an ascii to Metastock converter in python but am not having a lot of success. The file formats are http://sf.gds.tuwien.ac.at/00-pdf/m/mstockfl/MetaStock.pdf
by: Use*n*x | last post by:
Hello, I have a binary file (image file) and am reading 4-bytes at a time. The File size is 63,480,320 bytes. My assumption is that if I loop through this file reading 4 bytes at a time, I should loop 15,870,080 times. The code is: newprogram.cpp =============
by: Jeff | last post by:
Im trying to figure out why I cant read back a binary file correctly. I have the following union: #define BITE_RECORD_LEN 12 typedef union { unsigned char byte; struct { unsigned char type; /* 0 Type */ unsigned char sn; /* 1-3 Serial Number */
by: freeseif | last post by:
Hi programmers, I want read line by line a Unicode (UTF-8) text file created by Notepad, i don't want display the Unicode string in the screen, i want just read and compare the strings!. This code read ANSI file line by line, and compare the strings What i want Read test_ansi.txt line by line
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.