FileIOVersion3 - File Input/Output Up to this point you...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
File Input/Output Up to this point, you have been testing your programs by entering input from the keyboard. Although this works fine for small sets of input, this would be very time consuming for processing large amounts of data. Furthermore, large amounts of data often already exist in text files. It would certainly be wasteful to type these data in by hand while running a program when they are already available in a file. As you might imagine, C provides the ability to read from files, (AND write to files.) In fact, when we read information from the keyboard and wrote information to the screen, we primarily used the functions printf scanf Similarly, for reading from files and writing to files, we'll use the functions fprintf fscanf The first f in each of these function calls stands for "file." Here is the specification for each function: fprintf( file_ptr, ctrl_str, other_arguments ) fscanf( file_ptr, ctrl_str, other_arguments ) You'll notice that these are identical to printf and scanf EXCEPT for the first parameter.
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
How to Create a File Pointer In order to read from a file, or write to a file, you MUST use a pointer to that file. Here is a declaration of a file pointer: FILE *ifp; In order to properly "initialize" an file pointer, it must be set to point to a file. In order to do this, we must specify the following: 1) Name of the file 2) Mode ("r" for read or "w" for write) There is a function call that uses this information to open the appropriate file and return a pointer to it. It's name is fopen. Here is an example of its use: ifp = fopen("input.txt", "r"); You'll notice that the first parameter to the fopen function is a string storing the name of the file to be opened. The second parameter is also a string. For our purposes, this string will either be "r" or "w". (There are other possibilities for this second parameter, but we won't deal with them in this class.)
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

Page1 / 9

FileIOVersion3 - File Input/Output Up to this point you...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online