Chapter 22.7 Answers (contd)
2.7-P1 In our programs done in class and in the Labs, we have been prompting for input, getting the input, and echoing it. To convert such a program to a batch program that works best with input redirection, all we need to do is remove the prompting statements from the program, since we dont need to prompt when input comes from a file.
To convert the programs in the text, we also remove the prompting statements. Then, if the program does not echo its input already, we add statements that echo the input after it has been read, just as we already do in our in-class programs.
2.7-P1 To turn most any program into one using a program-controlled input and output file, including the program in Figure 2.12, make these changes:
1) First turn the interactive program into a batch program by removing the existing prompts and making sure there are statements that echo the input. Test the program using input redirection to make sure that it works and that all the input echoes properly when reading from a batch file supplied on the command line: C: myprog <
2) Add declarations for the input and output file pointers to the existing declarations:
FILE *infile, *outfile;
3) Add statements to open the input and output files, just before the first use of printf() or scanf():
infile = fopen(myinput.txt, r);
outfile = fopen(myoutput.txt, w);
Note how these statements use the file pointers you declared. One statement opens a file for reading, the other opens a file for writing.
4) Change all the scanf() function calls to use fscanf() with the input file pointer as the first argument, e.g. the first one would look like this:
fscanf(inputfile, %c%c%c, &first, &middle, &last);
This change makes the program read from the input file instead of from the standard input.
5) Change all the printf() function calls that are echoing the input to use fprintf() with the output file pointer as the first argument, e.g. the first one would start something like this:
fprintf(outputfile, Hello %c%c%c, lets see . . .
This change makes the program write to the output file instead of to the standard output. Note that if you left the existing printf() statements there and added new fprintf() statements, your program would echo the input to both the output file and to the standard output.
6) Close the input and output files just after the last use of the file pointers in your program:
fclose(inputfile);
fclose(outputfile);
7) Thats all! You have converted the program to open files and use those files for input and output, instead of reading from standard input and writing to standard output.