David Chu
David Chu

Reputation: 1

Problems reading a binary file with fread function

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.

Upvotes: 0

Views: 1358

Answers (1)

paxdiablo
paxdiablo

Reputation: 881103

"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.

Upvotes: 2

Related Questions