Text I O and Files 9 28 2007 1 Opening Discussion Let s look at solutions to the interclass problem Do you have any questions about the assignment 2 Why Files This should be an easy one As you know when a program stops running all the memory is lost and anything that you haven t written to disk is lost In Linux we can get some file access through I O redirection but then reading from a file means no keyboard input and writing to a file means nothing comes up on screen We d like to be able to use files for reading and writing in addition to the standard input and output 3 Streams Constructs that allow us to do input and output are referred to generally as streams In C we have text and binary streams and they are represented by the type FILE FILE is something defined in stdio h and the means it is a pointer The stdio library also defines several streams for us stdin stdout and stderr We can use these to refer to standard input output and error 4 Files When we want to work with files we have to get hold of streams connected to the files We do this with the fopen function Let s look at man to see how it works The first argument to fopen is the name of the file The second argument is what we intend to do with it Mode can be w a or r for write append or read A with w or r tells it to allow both Style can be t or b for text or binary After you are done using a stream that you get with fopen you need to close it with fclose 5 Formatted File I O When you are working with files you use fprintf and fscanf instead of the regular printf and scanf They work the same way but take an extra argument The first thing you pass them needs to be the FILE of the stream you want to use Note that fprintf stdout does exactly the same thing printf does and fscanf stdin does what scanf does This way you can write a function that does formatted I O and have it take a stream then use it either for files keyboard input or screen output 6 Minute Essay How confident do you feel about the midterm right now Remember to turn in assignment 3 by midnight tonight Interclass Problem Write a program that reads numbers from a file called numbers txt It should write numbers out to files called even txt and odd txt with the appropriate numbers going to each one 7
View Full Document