PROBLEM:
Write a program which reads in text from a file character by character and then writes out the text to another file, but this time in CAPITAL (or UPPER case) letters.
The input and output filenames will be specified as command line arguments.
You will need to use the function toupper(). This function is declared in ctype.h. It is sent a character and returns the character in upper case through the type specifier.
You will need to use the fgetc() function to preserve the white spaces.
Create your own input file - ie. in nedit create a file called test_in and type in some text. For example
The cat sat on the mat
The output file obtained by running the program should then contain
THE CAT SAT ON THE MAT
SOLUTION:
The first thing the program should do, is check the number of command line arguments and ensure that it is correct (In this case 3 - program name, input filenmae and output filename). It can then open the input and output files and check that they have been opened, if they are not correctly opened the progarm will stop.
The program can then proceed and read character by character from the input file. Each character read will then be converted to a capital letter and written to the output file before the next character is read in.
#include <stdio.h> #include <ctype.h> main(int argc, char *argv[]) { FILE *fi, *fo; char lower, upper; /* Check if number of arguments is correct */ if (argc != 3) { fprintf(stderr,"USAGE: program input_file output_file\en"); exit(1); } /* Open input file and check if opened OK */ if ((fi = fopen(argv[1],"r")) == NULL ) { fprintf(stderr,"Can't open file %s for reading\n",argv[1]); exit(1); } /* Open output file and check if opened OK */ if ((fo = fopen(argv[2],"w")) == NULL ) { fprintf(stderr,"Can't open file %s for writing\n",argv[2]); exit(1); } lower = fgetc(fi); while (!feof(fi)) { upper = toupper(lower); fprintf(fo,"%c",upper); lower = fgetc(fi); } fclose(fi); fclose(fo); }
Note carefully the loop for reading in and converting the characters. The loop is written in this way to ensure that the End of File is correctly detected. C programs will not detect the end of file until they have tried to read the end of file. Therefore, you will not that the order ensures that the next step afet reading a characetr, is checking if it is the end of file. This is illustrated in the figure below.
If the code had been written as
while (!feof(fi)) { lower = fgetc(fi); upper = toupper(lower); fprintf(fo,"%c",upper); }
This would have produced an additional characetr on the end of the output file, since it would have read the end of file character, tried to convert it to upper case and written it to the output file before it checked if it was the end of file. As shown below
If reading values from a file and checking for the end of file always be careful of the End of File Character and take care in the order in which you construct any loops
Back to Main Page for Lecture 8 |