Chapter 7Text Input/OutputCS 159 - C ProgrammingStandard I/O▪ Standard input and output streams are automatically provided to the program by the operating system▪ Standard input and output streams in C is provided by <stdio.h>• scanf automatically reads from stdin• printf automatically writes to stdoutstdinstdoutscanf()printf()#include <stdio.h>#define EXIT -1int main(void){int score = 0;int count = -1;float total = 0;do{count++;total += score;printf("Enter the score: ");scanf("%d", &score);} while (score != EXIT);printf("The average is: %.2f\n", total / count);return 0;}▪ Testing by hand▪ Testing by data filetestdata▪ Programs are repeatedly the same data sets in order to ensure the same conditions occur for testinga.outEnter the score: 4Enter the score: 5Enter the score: -1The average is: 4.504 5 -1a.out < testdataEnter the score: Enter the score: Enter the score: The average is: 4.50RedirectionRedirection – command-line function of an operating system that can reroute the standard input or output to user-specified locations. SymbolDescription<Redirect standard input from specified source. If the file doesn't exist, an error is given.>Redirect standard output tospecified source. If the file already exists, it is erased and overwritten. If the file doesn't exist, it is created. <<Redirect standard input from inline stream betweendelimiters.>>Redirect standard output toappend data to specified source. If the file doesn't exist, it is created.|Receive output from one source and use it as input to another source.Redirectiona.out <inputfilea.out >outputfilea.out <inputfile >outputfilea.out >>outputfilea.out <inputfile | morea.out << _? line1? line2?_File Input/Output▪ When to use redirection in a program?• A program produces so much output that it scrolls off of the screen• A program access too much data to be typed in by hand• You grow weary from typing in the same input data over and over againFiles▪ The "type" of file is determined by how it is treated by the application• Text file – sequence of lines made up of ASCII characters terminated by a new-line character (.txt)• Binary file – series of 1's and 0's representing various types of data fields (.mp3, .avi, .exe, .jpeg, etc.)▪ The only files we will deal with in this course are text filesFile – a named collection of data, typically contained in non-volatile secondary storage.File Handling▪ Declare the file▪ Open the file (and test for success)▪ Process the file▪ Close the fileDeclare the File▪ The variable is a pointer to the data streamFILE* inputFile;FILE* outputFile;Open the File▪ The location of file follows the conventions of the operating system▪ The predefined standard IO streams stdin/stdoutcan also be explicitly accessed if so desired. inputFile = fopen("c:\\project\data.txt","r");inputFile = fopen("/project/labData","r");outputFile = fopen("output.txt","w");inputFile = stdin;outputFile = stdout;“Error: file not found.Should I fake it? (Y/N).”Open the FileProgram Standards: If a file is opened with the fopen statement, the result must checked to sure that the file exists before proceeding in the program.inputFile = fopen("testInput","r");if (!inputFile){printf("Could not open input file\n");exit(1);}fopen ModesModeDescriptionrRead – If the file exists, the marker is positioned at the beginning. If the file doesn't exist, an error is given.wWrite – If the file exists, it is erased and the marker is positioned at the beginning. If the file doesn't exist, it is created. aAppend – If the file exists, the marker is position at the end. If the file doesn't exist, it is created. EOFEOFEOFFileMarkerFileMarker"r" Mode "w" Mode "a" ModeFileMarkerProcess the File▪ Use fscanf to read from a specific file stream until EOF is reached.▪ Use fprintf to write or append to specific file stream. EOF is automatically added when the file is closed.▪ All of the formatting codes for scanf/printf work the same for fscanf/fprintf .Standard Input/OutputGeneral Input/Outputscanf("string",...);printf("string",...);fscanf(stream,"string",...);fprintf(stream,"string",...);Conversion Codes%FlagWidthPrecisionSizeCode* suppresshhcharh shortl longlllong longL long doublec chard intu unsigned intf floats stringp pointer%FlagWidthPrecisionSizeCodepadding-left justify+ show sign0 padding.nhhcharh shortl long intlllong longL long doublec chard intu unsigned intf floats stringp pointerscanf/fscanfprintf/fprintfProcess the File▪ Typically use a while loop and go until EOF is reach▪ Normally should not assume that the file contains a certain number of lines (i.e. don't use a for loop)while (fscanf(inputFile,"%d",&num) != EOF){fprintf(outputFile,"The number was %d\n",num);}Close the File▪ It is considered bad form to rely on the operating system to close the file▪ "File locked by another user" messagefclose(inputFile);fclose(outputFile);Program Standards: Every file that is opened with the fopenstatement must later be explicitly closed with the fclosestatement.#include <stdio.h>#include <stdlib.h>int main(void){FILE* spInput;FILE* spOutput;int num;spInput = fopen("testInput","r");if (!spInput){printf("Could not open input file\n");exit(1);}spOutput = fopen("testOutput","w");if (!spOutput){printf("Could not open output file\n");exit(1);}while (fscanf(spInput,"%d",&num) != EOF){// only prints out the odd numbersif (num % 2)fprintf(spOutput,"%d\n",num);}fclose(spInput);fclose(spOutput);return 0;}#include <stdio.h>int main(void){FILE* append;int num;append = fopen("numbers.dat","a");if (!append){printf("Could not open input file\n");exit(1);} printf("Please enter a number\n");while (scanf("%d", &num) != EOF) // ^d terminates{fprintf(append,"%d\n",num);printf("Please enter a number\n");}fclose(append);return 0;}scanf/fscanf Considerations▪ The scanf/fscanf function returns the number of items read▪ The EOF marker (value -1) is returned when there is no more data to be readstatus = scanf("%d %d",&num1, &num2);Inputstatusnum1num245 272452725 A125?A B0??^d-1??scanf/fscanf Considerations▪ Both scanf and fscanf functions use an address list▪ A whitespace character in an input format string causes consecutive whitespace characters to be discarded▪ The number, order, and type of the conversion specifications must match the number, order, and type of the parameters in the list. Otherwise, the result will be unpredictable.▪ You can use the * flag to skip over a
View Full Document