#include #include void help(char *name) { fprintf (stderr, "Usage: %s [-v] [-o OFILE] [-c CHARS] FILE1 ... FILEn\n", name); fprintf (stderr, "Write some characters to OFILE (or standard output)\n"); fprintf (stderr, " -v : Verbose mode\n"); fprintf (stderr, " -o OFILE : select output file\n"); fprintf (stderr, " -c CHARS : select number of characters to read per input file\n"); } int main (int argc, char *argv[]) { char *outfile = NULL; int chars = 1; int verbose = 0; char *files[argc]; int numfiles = 0; // Set up the list of input files for (int i = 0; i < argc; i++) { files[i] = (char *) 0; } // for // Process the command line for (int i = 1; i < argc; i++) { if (argv[i][0] == '-') { char flag = argv[i][1]; switch (flag) { case 'v': verbose = 1; break; case 'o': if (argv[i][2] == 0) { outfile = argv[++i]; // Ugh } else { outfile = argv[i] + 2; } break; case 'c': if (argv[i][2] == 0) { chars = atoi (argv[++i]); } else { chars = atoi (argv[i] + 2); } break; case 'h': help (argv[0]); exit (EXIT_SUCCESS); break; default: fprintf (stderr, "Invalid flag: '%s'\n", argv[i]); help (argv[0]); exit (EXIT_FAILURE); break; } // switch } // if we have a dash else if (argv[i][0] == 0) { fprintf (stderr, "Empty strings not permitted.\n"); help (argv[1]); exit (EXIT_FAILURE); } else { files[numfiles++] = argv[i]; } // if we don't have a dash } // for if (verbose) { fprintf (stderr, "Verbose mode on.\n"); fprintf (stderr, "Characters to copy: %d\n", chars); fprintf (stderr, "Files to use: %d\n", numfiles); if (outfile) { fprintf (stderr, "Printing output to %s\n", outfile); } else { fprintf (stderr, "Printing output to stdout.\n"); } } // if (verbose) // Prepare output FILE *target = stdout; if (outfile) { target = fopen (outfile, "w"); } // Copy characters for (int i = 0; i < numfiles; i++) { if (verbose) { fprintf (stderr, "Copying from %s\n", files[i]); } // if verbose FILE *source = fopen (files[i], "r"); for (int ch = 0; ch < chars; ch++) { putc (getc (source), target); } // for ch fclose (source); } // for i // Clean up if (outfile) { fclose (target); } exit (EXIT_SUCCESS); } // main