File I O 9 28 2006 1 Opening Discussion What is recursion What things can recursion do that standard loops can t Why can it do those things Let s write Fibonacci using a recursive function and trace it Do you have any questions about the assignment Do you have any questions about the midterm 2 Dealing with Files Last time we discussed how adding file manipulation can make our programs much more powerful The functionality we want is actually part of the stdio library We represent a file by declaring a variable of type FILE The asterisk means it is a points We ll learn exactly what that means later on Use fopen to initialize your FILE It takes a file name and a string giving the mode The mode is a combination of the characters r w a t b When you are done with the file you need to pass the FILE to the fclose function 3 Writing and Reading Once you have opened the file you need to be able to either write to it or read from it We do this with functions very similar to printf and scanf Actually printf and scanf are have aliases for these other functions The fprintf and fscanf functions take a FILE as their first argument The rest of the arguments are just like printf and scanf Let s use this to get one of our programs to read from a file or write to a file 4 Standard Streams There are actually standard names for file streams that represent standard input and output The name stdin can be used to read from standard input The name stdout can be used to write to standard output 5 Coding Let s write something more significant and potentially a bit more fun that will use some files Remember that the real benefit of files is to store things between uses of a program 6 Arrays After the midterm we will be talking about arrays These structures give us a way to hold multiple things us the same type Consider if I wanted you to write a program to read in 100 numbers and do many different things with them How would you do that given what we have learned so far It s possible but it definitely wouldn t be pretty 7 Minute Essay Remember that the midterm is next Tuesday I plan to have a review session starting at 4 30 on Monday I don t prepare anything for the review sessions I expect you to show up with questions that you would like me to answer Also remember that assignment 3 is due tonight I should be around some this afternoon to answer questions 8
View Full Document