In C, you can manage files by declaring a pointer of type FILE and utilizing the fopen() function for creating, opening, reading, and writing to files.
FILE *fptr fptr = fopen(filename, mode); |
FILE is a data type used for file handling, and we typically create a pointer variable (fptr) of type FILE to work with it. This line is not crucial for now; it’s simply a prerequisite for file operations.
To open a file, utilize the fopen() function, which requires two parameters:
Parameter | Description |
filename | The filename of the specific file you wish to open or create, such as filename.txt |
mode |
A single character indicating the desired file operation:
|
To create a file, employ the ‘w’ mode within the fopen() function.
The ‘w’ mode is employed for writing to a file. If the file does not exist, it will be created:
FILE *fptr;
// Create a file // Close the file |
Note: If no specific path is provided, the file will be created in the same directory as your other C files. On our computer, it appears as follows: |
Tip: To create the file in a particular directory, specify an absolute path.
fptr = fopen(“C:\directoryname\filename.txt”, “w”); |
Closing the fileDid you observe the fclose() function in the example provided earlier? It’s responsible for closing the file once we’re finished using it. It’s regarded as good practice because it ensures that:
|
In the forthcoming chapters, you’ll discover how to write data to a file and retrieve information from it.