My question is why fstream can't read 0x1a. For example make a test file and inside it write in HEX editor 30 1A.

#include <iostream>
#include <fstream>
typedef unsigned long DWORD;

using namespace std;
fstream myfile;
template <class T>
T grad(T value, int step)
{
	T val(value);
	if(!step)
		return 0;
	--step;
	while(step--)
		value=value*val;
	return value;
}
// Get a word\dword from file in unsigned long
DWORD word(fstream *mu, unsigned long pointer, bool doubl)
{
	DWORD VALUE(0);
	int limit;
	if(doubl)
		limit = 4;
	else
		limit = 2;
	for(int i(1); i<limit; ++i){
		mu->seekg(pointer+i,ios::beg);
	    VALUE+= mu->get()*grad<long>(256, i);
	}
	mu->seekg(pointer,ios::beg);
	VALUE+= mu->get();
	return VALUE;
}
void main(void)
{
	
	myfile.open("D:\\test.gh", ios::in | ios::out );
	if(myfile.is_open())
	   cout<<word(&myfile, 0, 1);
	else
	   cout<<"Can't open this file!";
	system("PAUSE");
}

Here is the example file inside["D:\\test.gh"]:
30 1A 00 00 00 00 00 00 00 00

And the result in Cmd prompt:

4278124287

Someone can explain this please?

0x1A is the ASCII value for Ctrl+Z, which is the end-of-file character for a text stream on Windows. Since you're doing arbitrary seeking on the file anyway (an operation that's undefined for text mode streams), you can open the file as binary and that will fix the problem of 0x1A as well:

myfile.open("D:\\test.gh", ios::in | ios::out | ios::binary);

Thank you so much Narue! This solves my problem.

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.