Search⌘ K

Input and Output with Files

Learn to read and write data to files using fopen and fclose in C.

Opening and closing files with fopen and fclose

Before a file can be read or written to, it has to be opened using the fopen function, which takes as arguments a string corresponding to the file name, and a second argument (also a string) corresponding to the mode in which the file is accessed. The mode can be specified, for example, as read ("r"), write ("w") or append ("a"). The fopen function then returns a pointer to the (open) file. After reading and/or writing to a file, we need to close it using the fclose function.

Reading and writing to files

There are many functions in stdio.h for reading from and writing to files. There is a collection of functions for reading and writing ASCII (text) data as well as for handling binary data. ...