Archived

This topic is now archived and is closed to further replies.

H4ck3r

Reading a file -> What am I doing wrong?!

Recommended Posts

To read a binaryfile, I use this code: FILE* file = fopen("C:\\test.exe", "rb"); if(file == NULL) return 0; fseek(file, 0, SEEK_END); int nSize = ftell(file); fseek(file, 0, SEEK_SET); char *pText = new char[nSize]; fread(pText, sizeof(pText), nSize, file); fclose(file); It does pass the script (doesn''t quit by return 0), but the pText will remain the same (ÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ, but longer). What am I doing wrong? Maybe the SEEK_SET doesn''t work? How can I fix this?

Share this post


Link to post
Share on other sites
pText is a 32-bit pointer to the first element of an array, so sizeof(pText) == 4. You should be using sizeof(*pText).
You already know you are going to read chars, so use 1 (a char is 1 byte long) instead of sizeof(whatever).

I believe it should work, now...

ToohrVyk
-------------
Extatica - a free 3d game engine
Available soon!
Click here to learn more

Share this post


Link to post
Share on other sites
So you mean I have to use:
FILE* file = fopen("C:\\test.exe", "rb");
if(file == NULL)
return 0;
fseek(file, 0, SEEK_END);
int nSize = ftell(file);
fseek(file, 0, SEEK_SET);
char *pText = new char[nSize];

fread(pText, sizeof(*pText), nSize, file);
fclose(file);
Or you mean that I have to use:
FILE* file = fopen("C:\\test.exe", "rb");
if(file == NULL)
return 0;
fseek(file, 0, SEEK_END);
int nSize = ftell(file);
fseek(file, 0, SEEK_SET);
char *pText = new char[nSize];

fread(pText, 1, nSize, file);
fclose(file);

Both, they don't work: pText will become MZ (and so the length will be 3)....

[edited by - h4ck3r on December 26, 2002 7:35:06 AM]

Share this post


Link to post
Share on other sites
I assume you're reading in an EXE, yeah? Check nSize, it should be the 'real' size. Also check the return value of fread(), it'll tell you how many chars were read.
You're reading in a char string, which is NULL terminated. That means that when you read a hex value of 0x00, all the string functions (including printf(), the MSVC debugger, and whatever you're using to display the string) assume the string has finished, and don't display any more.

You can do this:
      
for(int i=0; i<nSize; ++i)
printf("%02X ",pText[i]);
to show the hex values of the text.

HTH

Edit: BTW, my hex editor shows that the first 16 bytes in telnet.exe are:
4D 5A 90 00 03 00 00 00 04 00 00 FF FF 00 00
You can see that the 4th value is 0x00 - which is the NULL terminator.



[edited by - Evil Bill on December 26, 2002 11:12:42 AM]

Share this post


Link to post
Share on other sites