/** * command-line.c * A simple example of command-line processing in C. Reads various * flags from the command line and prints out info on those flags. */ #include void helper (FILE *fp) { int ch; while ((ch = fgetc(fp)) != EOF) putc (ch, stdout); } // helper int main (int argc, char *argv[]) { int i; int reverse = 0; // Are we sorting in reverse mode? int numeric = 0; // Are we sorting in numeric mode? int width = 256; // The width of a line char *filename = NULL;// The name of the file we want to sort. FILE *fp; // The file we're sorting. // Parse the command line for (i = 1; i < argc; i++) { if (strcmp (argv[i], "-r") == 0) reverse = 1; else if (strcmp (argv[i], "-n") == 0) numeric = 1; else filename = argv[i]; } // Do something with the parsed command line info if (reverse) printf ("Reverse "); if (numeric) printf ("Numeric "); printf ("Sorting of "); if (filename) printf ("the file %s", filename); else printf ("stdin"); printf ("\n"); // Use the specified file, if given if (filename) fp = fopen (filename, "r"); else fp = stdin; if (fp == NULL) { printf ("No such file: %s\n", filename); return 1; } // Do the real work helper (fp); // Clean up after ourselves if (filename) close (fp); // And we're done return 0; } // main