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;
	
	
	}

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;
    
    
    }

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));
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.