CIS 71 (section 1): Homework 8 - Hints

  1. Using command line parameters
    Here is an example of a program that makes sure that you have a command line parameter and prints out its value:
         #include <stdio.h>
         int main (int argc, char *argv[]){
            if (argc != 2) {
               printf("Usage: %s filename\n", argv[0]);
               exit(0);
            }
            printf("You have typed:\n"
                   "\t%s %s\n", argv[0], argv[1]);
    
    For example, if this program is compiled into a.out we will have:
         % a.out
         usage: a.out filename
    
         % a.out hmw8.c
         You have typed
             a.out hmw8.c
    

  2. Printing out a text file
    Here is a program that prints out a text file [just like the cat command]:
    
       #include <stdio.h>
       int main (int argc, char *argv[]){
          FILE *fp;
          char c;
    
          if (argc != 2) {
             printf("Usage: %s filename\n", argv[0]);
             exit(0);
          }
    
          if ((fp = fopen(argv[1], "r"))==NULL) {
            perror("fopen");
            exit(1);
          }
          while((c=getc(fp))!=EOF)
            putchar(c);
          fclose(fp);
       }