Data stored in variables and arrays is temporary—it disappears the moment your program terminates. To make data persistent across program executions, we need to save it to files on the hard drive.
In this tutorial, we will learn how to create files in C using the standard I/O library (<stdio.h>). Understanding file creation is vital for building applications that generate logs, save user configurations, or export data.
FILE PointerIn C, all file operations revolve around a special data structure called FILE. To interact with a file, you must first create a pointer of type FILE. This pointer will keep track of the file's location, the current position within the file, and its status (e.g., end-of-file, error flags).
FILE *fptr;
fopen() to Create a FileTo create or open a file, we use the fopen() function.
fptr = fopen("filename.txt", "mode");
filename.txt: The name (and optionally the path) of the file you want to create.mode: A string representing what you want to do with the file.To specifically create a new file, you will generally use one of the following modes:
"w" (Write Mode): Creates an empty file for writing. If a file with the same name already exists, its contents will be erased (truncated to zero length)."a" (Append Mode): Opens a file for writing at the end of the file. If the file does not exist, it creates it. This is safer if you don't want to accidentally erase existing data."w+" (Write + Read): Creates an empty file for both reading and writing. Existing files are erased.Let's look at a complete example of creating a file named data.txt.
#include <stdio.h> #include <stdlib.h>int main() { FILE *fptr; // Create a new file (or overwrite an existing one) fptr = fopen("data.txt", "w"); // Always check if the file was successfully created! if (fptr == NULL) { printf("Error: Could not create file!\n"); return 1; // Exit with an error code } printf("File 'data.txt' created successfully!\n"); // Close the file when done fclose(fptr); return 0; }
NULL?When you call fopen(), it asks the operating system to create or open the file. This can fail for several reasons:
If it fails, fopen() returns NULL. If you try to write data to a NULL pointer, your program will crash (Segmentation Fault). Always check for NULL!
fclose()Notice the fclose(fptr); statement at the end of the example. When you are done with a file, you must close it.
Closing a file does the following:
fclose() forces any remaining data to be written to the hard drive immediately.When you pass "data.txt" to fopen(), C creates the file in the current working directory (usually the folder where your program was executed). This is called a relative path.
If you want to create the file in a specific folder, you must use an absolute path.
What happens if you use fopen() with the "w" mode on an existing file?