Solution for Exercise 22-11

ex2211

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[])
{
    char filename[255];
    FILE *dumpme;
    int x,c;

    /* Check for any command line arguments */
    if(argc<2)
    {
        /* prompt the user */
        printf("File to dump: ");
        scanf("%s",filename);
    }
    else
    {
        /* copy the argument to the filename */
        strcpy(filename,argv[1]);
    }
    
    /* open the file */
    dumpme=fopen(filename,"r");
    if(!dumpme)
    {
        printf("Unable to open '%s'\n",filename);
        exit(1);
    }

    /* dump the data */
    x=0;
    while( !feof(dumpme) )
    {
        c=fgetc(dumpme);
        if( c==EOF )
            break;
        printf("%02X ",c);
        x++;
        if(!(x%16))
            putchar('\n');
    }
    putchar('\n');
    fclose(dumpme);

    return(0);
}

Output

./a.out hello.txt
4C 6F 6F 6B 20 77 68 61 74 20 49 20 6D 61 64 65
21 0A 4D 79 20 43 20 70 72 6F 67 72 61 6D 20 77
72 6F 74 65 20 74 68 69 73 20 66 69 6C 65 2E 0A
54 68 69 73 20 74 65 78 74 20 77 61 73 20 61 64
64 65 64 20 6C 61 74 65 72 0A 54 68 69 73 20 74
65 78 74 20 77 61 73 20 61 64 64 65 64 20 6C 61
74 65 72 0A

Notes

* Because command line arguments are being read, the main() function's arguments must be specified (Line 5).

* The if-else structure beginning at Line 12 checks whether a filename argument was typed. If not, the code prompts for a filename.

* If a file name was typed, and assuming that it's the first command line argument, it's string is held in the argv[1] variable. That string is copied to the filename buffer at Line 21.