Files and Devices 

C Programming Tutorial 

Go to the Table of Contents


Files are places for reading data from or writing data to. This includes disk files and it includes devices such as the printer or the monitor of a computer. C treats all information which enters or leaves a program as though it were a stream of bytes: a file. The most commonly used file streams are stdin (the keyboard) and stdout (the screen), but more sophisticated programs need to be able to read or write to files which are found on a disk or to the printer etc.

An operating system allows a program to see files in the outside world by providing a number of channels or `portals' (`inlets' and `outlets') to work through. In order to examine the contents of a file or to write information to a file, a program has to open one of these portals. The reason for this slightly indirect method of working is that channels/portals hide operating system dependent details of filing from the programmer. Think of it as a protocol. A program which writes information does no more than pass that information to one of these portals and the operating system's filing subsystem does the rest. A program which reads data simply reads values from its file portal and does not have to worry about how they got there. This is extremely simple to work in practice. To use a file then, a program has to go through the following routine:

  • Open a file for reading or writing. (Reserve a portal and locate the file on disk or whatever.)
  • Read or write to the file using file handling functions provided by the standard library.
  • Close the file to free the operating system "portal" for use by another program or file.

A program opens a file by calling a standard library function and is returned a file pointer, by the operating system, which allows a program to address that particular file and to distinguish it from all others.