简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM