/* * Program to copy text from input to output, changing case of letters. * * Input: names of input and output text files. * * Output: text file with name as specified, contents same as input file, * but with uppercase letters have been changed to lowercase, and vice versa. */ #include #include #include #include #define FILENAME_LENGTH 100 /* safer way to get string from standard input: * * reads a whole line into "str" (maximum length array_length, including * '\0') * replaces '\n' (if found) with '\0' * * prints a warning message if no '\n' was found -- this indicates that * there was more input than would fit in str */ void my_get_string(char * str, int array_length) { char * newline_pos; fgets(str, array_length, stdin); newline_pos = strchr(str, '\n'); if (newline_pos != NULL) { *newline_pos = '\0'; } else { printf("warning: input truncated to %d characters\n", array_length-1); } } /* main program */ int main(void) { FILE * in; FILE * out; char in_name[FILENAME_LENGTH+1]; char out_name[FILENAME_LENGTH+1]; int input_char; /* get input, output file names */ printf("enter name of input file:\n"); my_get_string(in_name, sizeof(in_name)); printf("enter name of output file:\n"); my_get_string(out_name, sizeof(out_name)); /* open input file and check result */ in = fopen(in_name, "r"); if (in == NULL) { printf("unable to open input file %s\n", in_name); exit(EXIT_FAILURE); } /* open output file and check result */ out = fopen(out_name, "w"); if (out == NULL) { printf("unable to open output file %s\n", out_name); exit(EXIT_FAILURE); } /* read characters and copy to output, changing case */ while ((input_char = fgetc(in)) != EOF) { if(isupper(input_char)) { fputc(tolower(input_char), out); } else if (islower(input_char)) { fputc(toupper(input_char), out); } else { fputc(input_char, out); } } /* close files */ fclose(in); fclose(out); printf("All done!\n"); return EXIT_SUCCESS; }