0

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?

2
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by sasho648
0

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

Edited by Narue: n/a

This question has already been answered. 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.