File Basics

So far, whenever we wanted to use files, we needed to use indirection operators (< and >) to change standard input and standard output. This won't always be sufficient, though. Sometimes, we may want to read (or write) to more than one file. There are only a few commands you'll need to learn to use files:

FILE *fopen(char *fname, char *mode)
The fopen() function opens a file (what you'll need to do first.) It returns a pointer of type 'FILE' You don't need to worry about the details of the FILE type. Basically, it's just a structure that holds information about the file, such as whether it's open for reading or writing, its length, how many characters you've read from it, etc. The first argument to the function is the name of the file, which is a string. You can either hardcode the name of the file by typing it in your program (surrounded by double quotes) or pass the function a string-type variable with value equal to the name of the file. The mode argument specifies what 'mode' your file should be opened in - the most basic two modes are "r" and "w" (read and write.) Here are some examples:

fopen("myFile.txt","w");  //opens myFile.txt for writing
fopen(file, "r"); //assume file is a variable of type string - opens file for 
reading.

It's a good idea to check the return value to make sure the file was successfully opened. If the fopen() function fails for any reason, a null pointer is returned. (So your 'if' clause should compare the return value to NULL.) If the file is successfully opened, you'll want to save the file pointer that is returned so that you can do things with the file.) The above examples just open the files, and you don't save the value of the file pointer (so they are BAD.) Here's some sample code for opening a file. The variable name 'fp' is arbitrary. You can use any name you want to reference your file.

FILE *fp;
if ((fp = fopen("myFile", "r")) == NULL)
{
   printf("ERROR - myFile didn't open\n");
   exit(1);   //exit() is a function that terminates your program immediately.  
The value 1 is commonly used to indicate that an error occurred.
}

After successful execution of the fopen() command, we can now use our file pointer, 'fp' to access the file. There are several functions in the stdio library we can use. (Remember that we'll only be able to write to the file if we've opened it in 'writing' mode.) You should look in the appendix ofK&R for a full listing of the library functions. Here's a couple of them: