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

This is a discussion on Read/Write hex from/to a file in C? within the C Programming forums, part of the General Programming Boards category; Hello I've googled this but I'm not getting much joy. Does anyone know of an easy way to read/write hex ...

  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
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,473
    fscanf(f, "%x", &var); maybe
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  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
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,473
    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...
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  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, 09: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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21