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 filename, 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, and there are functions for dealing with binary data.

For ASCII files, there are functions to read and write single characters one at a time (getc and putc), there are functions to read and write formatted output (fscanf and fprintf), and there are functions to read and write single lines at a time (fgets and fputs).

Writing to an ASCII file

Here’s an example program that outputs a table of temperature values in Fahrenheit and Celsius to an ASCII file.

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy