Input and Output with Files

C also lets us read and write data to files using fopen() and fclose().

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. The mode is read (“r”), write (“w”) or append (“a”). The fopen() function then returns a pointer to the (open) file. After reading and/or writing to your file, you will 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.

Ascii Files (plain text)

There are functions to read single characters 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()).

Here is 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