/** * uc.c - Fun with uppercase. Takes a variety of strings (from the command * line, from the Makefile or stdin, elsewhere), converts them to uppercase, * and then prints them out. * * Sample command: * ./uc hello goodbye */ // +---------+-------------------------------------------------------- // | Headers | // +---------+ #include // For islower #include // For fun with input and output #include // For strchr #include "list.h" // We're working with lists // +-----------+------------------------------------------------------ // | Constants | // +-----------+ // The maximum length of a string #define MAXLEN 128 // +---------+-------------------------------------------------------- // | Helpers | // +---------+ /** * Convert a string to uppercase. */ int uc (char *str) { static int offset = 'A' - 'a'; // For each character in the string while (*str != '\0') { // If the character is lowercase if (islower (*str)) // Make it uppercase *str = *str + offset; // And move on to the next character. str++; } // while // Return 1 to match the requirements for foreach return 1; } // uc /** * Print out a horizontal rule of a particular length. */ void hrule (int len) { int i; for (i = 0; i < len; i++) putchar ('-'); putchar ('\n'); } // hrule /** * Print out a string on a line by itself. */ int print_string (char *str) { return printf ("%s\n", str); } // print_string // +------+----------------------------------------------------------- // | Main | // +------+ int main (int argc, char *argv[]) { struct list *lst; // A list of strings. char *line; // One line (for input) int i; // A favorite counter variable // Build the list. lst = list_new (); if (lst == NULL) { fprintf (stderr, "Could not create a list. Giving up!\n"); return 1; } // Add all of argv. for (i = 1; i <= argc; i++) list_append (lst, argv[i]); // Add some simple strings, such as our names. Include some lc and uc // and non-chars. list_append (lst, "Strongheart"); list_append (lst, "Strauna"); list_append (lst, "Green Eggs and Green Ham"); list_append (lst, "Latin@ is a *very* strange word. I'd give it a 8."); // Add the empty string list_append (lst, NULL); // Add the lines of the Makefile. (The Makefile is a file we know should // be in the current directory.) FILE *fp = fopen ("Makefile", "r"); if (fp == NULL) { fprintf (stderr, "Could not open the Makefile. Giving up.\n"); return 2; } while (fgets (line, MAXLEN, fp) != NULL) { // Drop the \n. *(strchr(line, '\n')) = '\0'; // Add it to the list. list_append (lst, line); } // Print out all of the strings hrule (80); list_foreach (lst, print_string); // Convert all of the strings to uppercase. list_foreach (lst, uc); // Print out all of the strings again hrule (80); list_foreach (lst, print_string); // And we're done return 0; } // main