0

What I want to do is to read the contents of a '.d' binary file and store them in an array. So I wrote the following codes:

void viewFile()
{
   unsigned char inFileData[SIZE];
   char fileName[SIZE];
   int numRead;

   FILE *inBinFile;


    printf("Enter the file name:");
    scanf("%s", fileName);

    inBinFile = fopen( fileName, "rb");
        if(( inBinFile = fopen(fileName, "rb")) == NULL )
        {
           fprintf( stderr, "Error opening %s\n", fileName );
           clearStdin();/*a function to clear stdin*/
           mainMenu();/*a function to prompt user input*/
        }
    numRead = fread( inFileData, sizeof(unsigned char), SIZE, inBinFile );
    inFileData[SIZE] = '\0';

    printf("U coded data:\n%s\n", inFileData);
    printf("%d\n", numRead);

    fclose(inBinFile);
   return;
}

the output is an unreadable pile of junk. Which part did I do wrong? I don't get it.

also, I wrote my clearStdin function as below:

void clearStdin(void)
{
    scanf("%*[^\n]");
    scanf("%*1[\n]");
   return;
}

compiler reported no errors, but somehow the function call doesn't seem to work exactly the way I wanted. It did clear stdin, but there are always errors closely following wherever this function is called, eg., the mainmenu function to prompt user input.

Please help!! thanks in advance.

8
  • 1
    Unless the contents of a binary file is a readable set of ASCII characters, sending the contents to stdout using a %s printf() format should generally result in an unreadable pile of junk. What is actually in the file? Commented Aug 22, 2012 at 6:38
  • What else would you expect - you said yourself the file was binary and so why would it yield readable output? Commented Aug 22, 2012 at 6:38
  • Is there a reason you open the file twice? Commented Aug 22, 2012 at 6:43
  • Micheal, the actual content is just 0 1 2 3 4 5 6 7 8 9. That's where I got confused.. thanks! Commented Aug 22, 2012 at 6:47
  • mathematician1975 the design specification said that the content is 0 1 2 3 4 5 6 7 8 9, so i want to print it... sorry for not making it clear enough and thank you! Commented Aug 22, 2012 at 6:48

1 Answer 1

2

"the output is an unreadable pile of junk" - yes, it will be. It's a binary file, it's not meant to be readable as text.

If you want to see binary information in a readable form, think about doing a hex dump of it.

See here for a way to do this.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.