Thread: converting a binary file to a text array

  1. #1
    Registered User
    Join Date
    Oct 2009

    converting a binary file to a text array

    Hello Everyone,

    I successfully used the following code to create a text file (for use in an assembly file) from a binary file.

    The problem is the code adds 2 extra bytes at the end (, 0xFFFF,). I think it has something to do with the EOF string, but I can't figure it out. I have tried for a few days now and I just can't see the problem.

    Can someone help me please?

    This code works and produces a text file from a binary file that looks like this:
    	.db	0x49, 0x44, 0x33, 0x03, 0x00, 0x00, 0x00, 0x00, 0x01, 0x76, 0x50, 0x52, 0x49, 0x56, 0x00, 0x00
    Here is the code:
    #include <stdio.h>
    /*program works good except we get an extra word at the end
    like this , 0xFFFF, (shouldn't be there at all)*/
    FILE *fin, *fout;
    int main(int argc, char **argv)
      unsigned short val, word_count;
    //  char buffer[10];
      char buffer[20];
      printf ("argv[1]=%s\n", argv[1]);
      fin = fopen(argv[1], "rb");
      fout = fopen(argv[2], "wt");
      word_count = 0;
     while (!feof(fin)) {
        if (word_count == 0) {
        val = fgetc(fin);
        if (word_count < 15) {
         sprintf(buffer, "0x%02X, ", val);
        else {
          sprintf(buffer, "0x%02X\n", val);
          word_count = 0;
        fwrite(buffer, 1, strlen(buffer), fout);
      return (0);

  2. #2
    Registered User
    Join Date
    May 2010
    Your problem is probably because of your use of !feof(fin) in your while loop. feof() will not fail until after you read past the end of file. See this link for a more detailed explanation.


  3. #3
    Registered User
    Join Date
    Oct 2009
    Thanks for the link Jim, I solved the problem after some reading.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Read text file and store it in an array
    By look2hook in forum C Programming
    Replies: 2
    Last Post: 12-03-2010, 11:47 PM
  2. Storing data from text file into array?
    By flaris in forum C Programming
    Replies: 6
    Last Post: 12-02-2010, 02:19 PM
  3. reading file characters into an int array
    By spongefreddie in forum C Programming
    Replies: 9
    Last Post: 10-28-2010, 12:23 PM
  4. Writing a text file to an array?
    By Raen in forum C Programming
    Replies: 11
    Last Post: 10-15-2010, 06:26 PM
  5. Ok, Structs, I need help I am not familiar with them
    By incognito in forum C++ Programming
    Replies: 7
    Last Post: 06-29-2002, 09:45 PM