954,219 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Skip initial 4 bytes in a binary stream

I have a binary file, contain set of stream, and I want to find some information there. What I have done up to now is read the file, open it and count the number of streams three. I'm stuck now.

Just consider one stream. I want to skip first 4 bytes and read the next 4 bytes. The second 4 bytes gives the length of the next part and that is the end of one stream. Same process should follows until EOF is found. My question is how to skip that first 4 bytes and point to the next byte.

eranga262154
Junior Poster
185 posts since Sep 2007
Reputation Points: 32
Solved Threads: 2
 

Just read 4 bytes and don't store the result ?

Or use a 'seek' function to advance the stream by 4 bytes ?

A bit of code to fill us in on exactly what kind of stream you're talking about might help.

Salem
Posting Sage
Team Colleague
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
 

Ok' I'll put mu code here. Actually I have no important on first four bytes. I need to read next four byes. Here what I have tried up to now.

#include <iostream>
#include <fstream>

using namespace std ;

int main ()
{
	ifstream fileopen ;
	char buffer[100 ] ;
	char c ;

	fileopen.open ( "G00046_002_01.srf", ios :: in | ios :: out | ios :: binary ) ;

	if(fileopen.is_open())
	{
		fileopen.seekg(0, ios :: beg) ; // Move pointer to the beginning
		while(!fileopen.eof())
		{
			fileopen.read(buffer, 50) ;
			fileopen.seekg(4) ;
			fileopen >> c ;        // Just to check the file read correctly 
			cout << c << endl ;

                       // Now I want to read the next 4 bytes here

		}
		fileopen.close() ;
	}

	else
	{
		cout << "Unable to open the file\n" ;
	}


	cin.get() ;
	return 0 ;
}


What is your suggestion for me.
Help appreciate

eranga262154
Junior Poster
185 posts since Sep 2007
Reputation Points: 32
Solved Threads: 2
 

line 16 is not needed because the file pointer is always set to beginning of file when the file is opened -- line 12.

line 17 is an infinite loop because lines 19 and 20 reset the file pointer back to the 4th byte in the file on every loop iteration. Suggestion: delete line 19 altogether because it isn't needed. Move line 20 outside the while loop, to line 16.

don't use eof() function because it doesn't do what you think it does. Code the loop like this

while( fileopen >> c)
{
   // blabla
}
Ancient Dragon
Retired & Loving It
Team Colleague
30,046 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,342
 

Thanks, I'll work with your suggestion and if I found any difficulties right back here.

eranga262154
Junior Poster
185 posts since Sep 2007
Reputation Points: 32
Solved Threads: 2
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You