0

Hi there,
in my binary file i want read something but from 4th byte.

i need to read data as 2 bytes int.

i have this code but im not sure if its ok:

some of my files should have some values less than 0, and im not getting any..so i believe my code is bad.....

fstream datafile("file.dat",ios::binary|ios::in);
	if (!datafile){
		cerr << "Error opening file!"<<endl;
		exit(1);
	}
for(i=4; i<100;i=i+2){
	datafile.seekg(i,ios::beg);
	datafile.read((char*)&dataCount,2*sizeof(char));
	
	
	cout << dataCount << ";" << endl;
	
	
	}
2
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by MasterGberry
0

i beleve this code is better, but also not sure if its correct:

short spremi; //  2 byte
        int dataCount; // 4 byte

        datafile.seekg(0,ios::beg);

        datafile.read(reinterpret_cast<char*>(&dataCount),4*sizeof(char)); // read 4 bytes
    
    
    
        //read 2 bytes    

        while(!datafile.eof()){
          datafile.read(reinterpret_cast<char*>(&spremi),2*sizeof(char));
    
    
           cout << spremi << endl;
    
    
    }
0

Here is an example that I used in my recent binary project

use sizeof(dataCount) instead of sizeof(char) because it depends on the compiler, although 2 and 4 are the standard.

Also using signed int garuntees that you can get negative values, your code looks fine though.

inFileDrs.read(reinterpret_cast<char*>(&tableCount),sizeof(tableCount));
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.