Thread: Read/Write hex from/to a file in C?

  1. #1
    Registered User
    Join Date
    Mar 2008
    Posts
    18

    Read/Write hex from/to a file in C?

    Hello

    I've googled this but I'm not getting much joy.

    Does anyone know of an easy way to read/write hex from/to a file in C?

    Thank you.

  2. #2
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    fscanf(f, "%x", &var); maybe
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  3. #3
    Registered User
    Join Date
    Mar 2008
    Posts
    18
    Thank you for your reply.

    So if I have a text file called plaintext.txt with the following HEX:

    0123456789ABCDEF

    Should the following code work?

    Code:
    FILE *fp;
    unsigned char message[8];
    
    fp=fopen("c:\\plaintext.txt", "r");
    fscanf(fp, "%x", &message);
    fclose(fp);
    Thank you
    Last edited by MrSteve; 03-25-2008 at 04:30 PM.

  4. #4
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    Should the following code work?
    no...
    read the scanf format description
    read about %x format
    read about maximum integer value
    try to figure out your problems...
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  5. #5
    Nub SWE
    Join Date
    Mar 2008
    Location
    Dallas, TX
    Posts
    133
    Here is the code, like yours, but it compiles:

    Code:
    #include <stdio.h>
    
    int main(void)
    {
    	FILE *fp;
    	unsigned int message;
    
    	fp=fopen("c:\\plaintext.txt", "r");
    	fscanf(fp, "%x", &message);
    	printf("%x ", message);
    	
    	fclose(fp);
    	
    	return 0;
    }
    Here is the output:
    Code:
    89abcdef
    Go from there. Looks to me like it's only printing the last 8 digits.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. opening empty file causes access violation
    By trevordunstan in forum C Programming
    Replies: 10
    Last Post: 10-21-2008, 11:19 PM
  2. Inventory records
    By jsbeckton in forum C Programming
    Replies: 23
    Last Post: 06-28-2007, 04:14 AM
  3. help with text input
    By Alphawaves in forum C Programming
    Replies: 8
    Last Post: 04-08-2007, 04:54 PM
  4. Possible circular definition with singleton objects
    By techrolla in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2004, 10:46 AM
  5. archive format
    By Nor in forum A Brief History of Cprogramming.com
    Replies: 0
    Last Post: 08-05-2003, 07:01 PM