Programmer's Wiki

fopen is the standard C function for opening or creating streams. It is primarily used for reading from and writing to files, though there are other uses as well.

Synopsis[]

#include <stdio.h>

FILE *fopen( const char *path,
             const char* mode );

Where path can be any valid file path (this is system-depedent), and mode can be any of the following:

  • "r" - Opens an existing file for reading. If the file does not exist, the function will fail.
  • "r+" - Opens the stream for reading AND writing
  • "w" - Open the stream for writing. If the file already exists, it will be erased. If it does not exist, it will be created.
  • "w+" - Open the stream for reading AND writing; if the file does not exist, it will be created.
  • "a" - Like "w", except that if the file exists new data will be written to the end of the file
  • "a+" - Open the stream for reading AND appending

Examples[]

The following example shows how to create a file, "my_file.txt", then write some text to it:

#include <stdio.h>              // Standard I/O functions
#include <stdlib.h>             // EXIT_SUCCESS and EXIT_FAILURE

int main()
{
	FILE* my_file = fopen("my_file.txt", "w"); // Attempt to create "my_file.txt"

	if( !my_file ){ // If my_file is NULL, then fopen() failed
		fputs("error: could not open my_file.txt for writing\n", stderr);
		return EXIT_FAILURE; // Exit unsuccessfully
	}

	fputs("some text\n", my_file); // Write "some_text" to my_file.txt
	fclose(my_file); // Closes the stream and flushes all buffers (writes changes to the file)

	return EXIT_SUCCESS;
}

See also[]