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;

    if(argc > 1)
    {
        strcpy(filename,argv[1]);
    }
    else
    {
        printf("File to dump: ");
        scanf("%s",filename);
    }
    dumpme=fopen(filename,"r");
    if(!dumpme)
    {
        printf("Unable to open '%s'\n",filename);
        exit(1);
    }
    x=0;
    while( (c=fgetc(dumpme)) != EOF)
    {
        printf("%02X ",c);
        x++;
        if(!(x%16))
            putchar('\n');
    }
    putchar('\n');
    fclose(dumpme);
    return(0);
}

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 11 checks to see whether a filename argument was typed. If not, the code prompts for a filename. The rest of the code is pretty much the same as for Exercise 22-10.

* 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 13.