Thread: Reading Hex Code from General Files HELP

  1. #1
    Registered User
    Join Date
    Jun 2013
    Posts
    6

    Reading Hex Code from General Files HELP

    I want to create a program that views the hex code of a file. When I finished the code, which is actually pretty simple, I executed the program and the only output that I got was an infinite loop that printed 0. Below is the source code:

    Code:
    #include <stdio.h>
    
    
    int main()
    {
    	int cnto = 0;
    	unsigned int i;
    	FILE * pFile = fopen("test.exe", "rt");
    	while(fscanf(pFile, "%X", &i) != EOF)
    	{
    		++cnto;
    		printf("%0x ", i);
    		if(cnto == 8)
    		{
    			printf("\n");
    			cnto = 0;
    		}
    	}
    	return 0;
    }
    I haven't included any error checker because there was no need. The pFile is located in the correct directory and it is opened successfully.

  2. #2
    Registered User migf1's Avatar
    Join Date
    May 2013
    Location
    Athens, Greece
    Posts
    385
    Try...

    Code:
    #include <stdio.h>
      
    int main( void )
    {
        int cnto = 0;
        unsigned char i;
        FILE *pFile = fopen("text.exe", "rb");
    
        while ( EOF != fscanf(pFile, "%c", &i) )
        {
            ++cnto;
            printf("%02X ", i);
            if (cnto == 8)
            {
                printf("\n");
                cnto = 0;
            }
        }
    
        fclose( fp );
        return 0;
    }
    I guess you are trying to display bytes in hex, so i better be defined as an unsigned char (if using C99, then by including <stdint.h> you could use uint8_t instead... or just %hhu for the scanf() ).

    PS. Btw, what file opening mode does "rt" represent? I' don't think that's a standard mode.
    Last edited by migf1; 06-06-2013 at 05:34 AM.

  3. #3
    Registered User
    Join Date
    Mar 2011
    Posts
    546
    when reading binary bytes, don't use fscanf. its extra overhead for nothing. how about this:

    Code:
    while(fread(&i,1,1,pFile) == 1) {
       printf("%02X",i);
       ...

  4. #4
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    Not only the extra overhead, but binary files can and often do contain values that will be misinterpreted by the formatted IO functions. For example fscanf() by default skips leading whitespace characters, which in most instances is not the behavior you want when dealing with binary files.

    Jim

  5. #5
    Registered User
    Join Date
    Jun 2013
    Posts
    6
    Quote Originally Posted by migf1 View Post
    Try...

    Code:
    #include <stdio.h>
      
    int main( void )
    {
        int cnto = 0;
        unsigned char i;
        FILE *pFile = fopen("text.exe", "rb");
    
        while ( EOF != fscanf(pFile, "%c", &i) )
        {
            ++cnto;
            printf("%02X ", i);
            if (cnto == 8)
            {
                printf("\n");
                cnto = 0;
            }
        }
    
        fclose( fp );
        return 0;
    }
    I guess you are trying to display bytes in hex, so i better be defined as an unsigned char (if using C99, then by including <stdint.h> you could use uint8_t instead... or just %hhu for the scanf() ).

    PS. Btw, what file opening mode does "rt" represent? I' don't think that's a standard mode.
    "rt" is same as "r" I just hoped that it might work with that one. By the way, it worked perfectly. Thank you very much.

  6. #6
    Registered User migf1's Avatar
    Join Date
    May 2013
    Location
    Athens, Greece
    Posts
    385
    A simple fgetc() should be fine for this case.

    Code:
    ...
        int i=0, c;
        FILE *fp = fopen("test.exe", "rb");
    
        while ( EOF != (c = fgetc(fp)) )
        {
            ++i;
            printf("%02X ", c);
            if (8 == i )
            {
                putchar( '\n' );
                i = 0;
            }
        }
    
        fclose(fp);
    ...
    PS. Glad I helped
    Last edited by migf1; 06-06-2013 at 10:48 AM.

  7. #7
    Registered User
    Join Date
    Jun 2013
    Posts
    6
    Quote Originally Posted by dmh2000 View Post
    when reading binary bytes, don't use fscanf. its extra overhead for nothing. how about this:

    Code:
    while(fread(&i,1,1,pFile) == 1) {
       printf("%02X",i);
       ...
    Quote Originally Posted by jimblumberg View Post
    Not only the extra overhead, but binary files can and often do contain values that will be misinterpreted by the formatted IO functions. For example fscanf() by default skips leading whitespace characters, which in most instances is not the behavior you want when dealing with binary files.

    Jim
    This one worked too. Thank you. But I have another question now. Is it the same with read()?

  8. #8
    Registered User migf1's Avatar
    Join Date
    May 2013
    Location
    Athens, Greece
    Posts
    385
    Quote Originally Posted by UXroot View Post
    This one worked too. Thank you. But I have another question now. Is it the same with read()?
    Pretty much, but read() operates with int file-handles instead of FILE * pointers. It is also non-portable, although most compilers provide it as an extension (some of them using and underscore as a prefix for its name: _read() ).

    In any case, both these functions are the norm because we rarely read files byte by byte (for byte by byte fgetc() is more handy and less verbose). We usually read files either as a whole into a buffer (this usually leads to simpler code) or gradually in blocks of bytes (this is often coupled with some "windowing" technique for handling parts of the file... i.e. "moving" the buffer over different parts of the file).

  9. #9
    Registered User
    Join Date
    Jun 2013
    Posts
    6
    Quote Originally Posted by migf1 View Post
    Pretty much, but read() operates with int file-handles instead of FILE * pointers. It is also non-portable, although most compilers provide it as an extension (some of them using and underscore as a prefix for its name: _read() ).

    In any case, both these functions are the norm because we rarely read files byte by byte (for byte by byte fgetc() is more handy and less verbose). We usually read files either as a whole into a buffer (this usually leads to simpler code) or gradually in blocks of bytes (this is often coupled with some "windowing" technique for handling parts of the file... i.e. "moving" the buffer over different parts of the file).
    So the difference between them is the variable. I see. Now there's another problem. I have made it to display the offset and the ascii content. The problem is that it displays the new lines as a new line. So I tried to solve the problem via printing a dot (.) everytime it finds the 0A value (new line) but it doesn't work... Below is the code:

    Code:
    #include <stdio.h>
    
    
    int main()
    {
    	int cnto = 0, l, prev = 8, nop = 0;
    	int offset = 0x00000000;	
    	unsigned char i[8];
    	FILE * pFile = fopen("test.exe", "rb");
    	while(fread(&i[cnto], 1, 1, pFile) == 1)
    	{
    		if(cnto == 0)
    		{
    			printf("%.8X\t", offset);
    		}
    		printf("%02X ", i[cnto]);
    		if(cnto == 7)
    		{
    			cnto = -1;
    			printf("    ");
    			for(l = 0; l <= 7; ++l)
    			{
    				if(i[l] != 0x00 || i[l] != 0x0A)
    				{
    					printf("%c ", i[l]);
    				}
    				else
    				{
    					printf(". ");
    				}
    				
    			}
    			printf("\n");
    		}
    		++cnto;
    		offset += 0x00000001;
    	}
    	fclose(pFile);
    	return 0;
    }

  10. #10
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    Code:
    if(i[l] != 0x00 || i[l] != 0x0A)
    This is alwais true
    try
    Code:
    if(i[l] != 0x00 && i[l] != 0x0A)
    Kurt

  11. #11
    Registered User
    Join Date
    Jun 2013
    Posts
    6
    Quote Originally Posted by ZuK View Post
    Code:
    if(i[l] != 0x00 || i[l] != 0x0A)
    This is alwais true
    try
    Code:
    if(i[l] != 0x00 && i[l] != 0x0A)
    Kurt
    Oh my. How didn't I see it?! Thank you very much!

  12. #12
    Registered User migf1's Avatar
    Join Date
    May 2013
    Location
    Athens, Greece
    Posts
    385
    Quote Originally Posted by UXroot View Post
    So the difference between them is the variable. I see.
    read() is closer to the metal, being a kernel system call on Unix/Linux platforms.

    Now there's another problem. I have made it to display the offset and the ascii content. The problem is that it displays the new lines as a new line. So I tried to solve the problem via printing a dot (.) everytime it finds the 0A value (new line) but it doesn't work...
    You may use...

    Code:
    #include <ctype.h>
    ...
    if ( isprint( (int)(i[l]) )
        printf("%c ", i[l]);
    else
        putchar( '.' );
    ...
    [offtopic]
    It looks like you are trying to make a hex viewer. If you are interested, here's a a little, x-platform hex-viewer for the console I wrote in C99 a year or two ago (I really don't remember ) in my spare time, just for fun.

    It comes with source-code, although big parts of it are left in "1st draft mode". Documentation is not that great either (just a few .txt files)... same goes for comments in the code (big parts of them have no comments at all).

    It also uses a tiny, autonomous x-platform preprocessor interface I wrote back then for color output on the console/terminal. A more recent version (not yet uploaded "officially" on my site) of that interface can be found here, while it's documentation is available online here.

    Unfortunately, I no longer have too much spare time (to fool around :P) so it's not likely I will improve any of them any time soon (and oh boy, they certainly need improvements).

    Nevertheless, perhaps (for some reason) they prove handy to somebody. So by all means feel free to play with them if you feel like it.
    [/offtopic]

  13. #13
    Registered User
    Join Date
    Jun 2013
    Posts
    6
    Quote Originally Posted by migf1 View Post
    read() is closer to the metal, being a kernel system call on Unix/Linux platforms.



    You may use...

    Code:
    #include <ctype.h>
    ...
    if ( isprint( (int)(i[l]) )
        printf("%c ", i[l]);
    else
        putchar( '.' );
    ...
    [offtopic]
    It looks like you are trying to make a hex viewer. If you are interested, here's a a little, x-platform hex-viewer for the console I wrote in C99 a year or two ago (I really don't remember ) in my spare time, just for fun.

    It comes with source-code, although big parts of it are left in "1st draft mode". Documentation is not that great either (just a few .txt files)... same goes for comments in the code (big parts of them have no comments at all).

    It also uses a tiny, autonomous x-platform preprocessor interface I wrote back then for color output on the console/terminal. A more recent version (not yet uploaded "officially" on my site) of that interface can be found here, while it's documentation is available online here.

    Unfortunately, I no longer have too much spare time (to fool around :P) so it's not likely I will improve any of them any time soon (and oh boy, they certainly need improvements).

    Nevertheless, perhaps (for some reason) they prove handy to somebody. So by all means feel free to play with them if you feel like it.
    [/offtopic]
    The code now works perfectly! Thank you very much for your help! And yes. You guessed right, that's exactly what I'm building. I am currently examining your code and testing it out. Thank for that. And by the way, it looks like we are both Greek. Σ' ευχαριστώ και πάλι!

  14. #14
    Registered User migf1's Avatar
    Join Date
    May 2013
    Location
    Athens, Greece
    Posts
    385
    You are welcome (καλησπέρα )

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. [Gravity] General Advice on Specific Code
    By M.Richard Tober in forum Game Programming
    Replies: 5
    Last Post: 01-10-2012, 06:19 PM
  2. [General Help] Dynamic Arrays and General Pointer syntax
    By Amberlampz in forum C Programming
    Replies: 22
    Last Post: 07-26-2011, 10:58 PM
  3. Replies: 6
    Last Post: 06-07-2010, 09:04 AM
  4. General Code review
    By twinz1978 in forum C Programming
    Replies: 1
    Last Post: 02-28-2006, 02:15 AM
  5. header files in general
    By Trauts in forum C++ Programming
    Replies: 6
    Last Post: 05-07-2003, 04:02 PM

Tags for this Thread