C Create Files

C Create Files: Interacting with the File System

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.


1. The FILE Pointer

In 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;

2. Using fopen() to Create a File

To create or open a file, we use the fopen() function.

Syntax:

fptr = fopen("filename.txt", "mode");

File Creation Modes

To specifically create a new file, you will generally use one of the following modes:


3. Example: Creating a New File

Let's look at a complete example of creating a file named data.txt.

File Creation Example

#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; }

Why Check for 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!


4. The Importance of 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:

  1. Flushes Buffers: C standard I/O is buffered. Data you write might sit in memory until the buffer is full. fclose() forces any remaining data to be written to the hard drive immediately.
  2. Releases Resources: The operating system places limits on how many files a program can have open simultaneously. Closing files frees up those system resources.
  3. Removes Locks: It releases the lock on the file, allowing other programs (or other parts of your program) to access it safely.

5. Absolute vs. Relative Paths

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.


Exercise

?

What happens if you use fopen() with the "w" mode on an existing file?