File I/O


The ability to read data from and write data to files is the primary means of storing persistent data, or data which does not disappear when your program finishes running.

The abstraction of files provided by the standard I/O library (stdio) is implemented in a structure called FILE. Calling fopen returns a pointer to the file you have just opened. If it returns NULL, then it could not open the requested file.

Almost all of the functions you’ll then use to manipulate your newly opened file take this file pointer as one of one of their arguments.

These functions allow us to read from or write to the file we’ve just opened.

Be sure to fclose any and all files that you have fopened.

UNIX will close any files you’ve left open when your program terminates, but it is considered poor coding practice to rely on this behavior.

In this program, we are storing the values of an array called scores in a file named database.

  • We open the file using the fopen function. The second argument "w" tells fopen that we want to write to this file. If a file named database does not already exist, fopen will create it.
  • if (file != NULL) is a sanity check that call to fopen didn’t fail.
  • fprintf takes a file pointer as its first argument. Instead of printing to the screen, fprintf prints to the file we pass to it.

This program opens each file whose name is specified in argv, reads into memory its characters, and prints those characters to stdout.

Slides ( / )

study50 slide
study50 slide
study50 slide
study50 slide
study50 slide
study50 slide


Implement cp.c, a program that takes two command line arguments — a source file and a destination file — and copies the contents of the source to the destination.

jharvard@appliance (~/Dropbox): ./cp original.txt copy.txt

Try out some pseudocode here!
Notice (8): Undefined index: default_code [APP/View/Elements/problem.ctp, line 38]
Notice (8): Undefined index: default_code [APP/View/Elements/problem.ctp, line 38]
To complete this problem, please download the distribution code.


study50 video thumbnail

Week 4, Monday

An introduction to file I/O
study50 video thumbnail

Jason's File I/O Short

Jason gives a general overview.