Logo  

CS256 - Fundamentals of Structured Programming

Displaying exercises/e9/solution/f2.c

#include <stdio.h>

/**
 * Make a program that takes a filename from the command line, or print the
 * usage message: "Usage: f2 <filename>\n" if it's absent.
 * Open the file for reading and read it one character at a time.  Use the
 * lrot (for lowercase letters) and urot (for uppercase characters) strings
 * to translate characters that you read and then output the translated
 * characters.  If the character read is not a letter, then output it as-is.
 * To translate a character, subtract either the lowercase 'a' (for lowercase
 * letters) or 'A' (for uppercase letters) to get it's index location in the
 * *rot string, i.e.: output lrot[ch-'a'] if the character in ch is lowercase.
 */
int main(int argc, char *argv[])
{
  char lrot[] = "nopqrstuvwxyzabcdefghijklm";
  char urot[] = "NOPQRSTUVWXYZABCDEFGHIJKLM";

  if (argc < 2) {
    printf("f2 <filename>\n");
    return 1;
  }

  FILE *fp = fopen(argv[1], "r");
  if (fp == NULL) {
    printf("Error opening file.\n");
    return 1;
  }
  
  int ch;
  while((ch = fgetc(fp)) != EOF) {
    if (ch >= 'a' && ch <= 'z') putchar(lrot[ch-'a']);
    else if (ch >= 'A' && ch <= 'Z') putchar(urot[ch-'A']);
    else putchar(ch);
  }
  fclose(fp);
  
  return 0;
}