scanf

Input can be handled with the scanf function, which behaves similarly to printf (as always, remember to #include <stdio.h> when using standard I/O functions):

As we discussed in the pointers section, variables must be handed to scanf with the address operator "&", as this operator gives a variable"s address in memory. The scanf function ignores blanks and tabs in its format string, and will skip over white space as it parses the requested input values.

Files

The previous examples have only shown reading input from the keyboard (standard input) and writing output to the screen (standard output). Next we will consider files as a source of input and destination for output. Before a file can be read or written to, it must be opened using the function "fopen". This function takes as arguments the name of the file to be opened and an "access mode" specifier.

fopen returns a pointer to be used for reads and writes and will return NULL if the file does not exist or if the user running the program does not have sufficient permission to access it. A good program will always check to make sure a file was opened before attempting to use it. Users don"t need to know all the details about the file, as this is handled in the stdio.h library which includes a structure called FILE.

Open file example

As mentioned above, the second argument of fopen is the access mode. There are 3 modes, which can be stacked, so you can do "rw" as well as just "r":

  • "r" opens a file for read only
  • "w" opens a file for write only (this will overwrite any previous contents, i.e. delete the content of the existing file)
  • "a" opens a file for appending (writing at the end of the file)

File pointers can be manipulated in the same fashion as I/O from the keyboard and the screen. The functions fscanf() and fprintf() can read from and write to, respectively, a file pointer. Both functions take the file pointer as their initial parameter.

The function fprintf() works like printf except that it writes to a file pointer rather than to standard out.

After you have opened and read or written to a file you will have to close it using the fclose() function. fclose() flushes the write buffer and closes the file:

Exit

On encountering an error (such as cannot open the file) we may want to "immediately exit" from the program, for this we will use the exit() function which is part of the stdlib.h library. The exit() function takes an integer error-value (here -1) which is returned to the operating system; most operating systems work under the convention that 0 is a normal exit status, whereas anything else is abnormal. The program being run may have documentation on what specific error codes mean..

 
©  |   Cornell University    |   Center for Advanced Computing    |   Copyright Statement    |   Inclusivity Statement