Working with Files in C
File handling in C enables you to store data permanently on a storage device. By using file operations, you can create, write, read, and manipulate files directly from your C programs.
Key Topics
1. Basic File Operations
The basic operations that can be performed on files are:
- Creating a new file
- Opening an existing file
- Reading from a file
- Writing to a file
- Closing a file
2. File Pointers
In C, files are managed using a file pointer of type FILE *
. This pointer is used to access and manipulate files.
FILE *fptr;
3. Opening and Closing Files
Files are opened using the fopen()
function and closed using the fclose()
function.
Example: Opening a File
FILE *fptr;
fptr = fopen("filename.txt", "r"); // Open file for reading
if (fptr == NULL) {
printf("Error opening file!\n");
exit(1);
}
File Modes
Mode | Description |
---|---|
"r" | Open for reading. The file must exist. |
"w" | Open for writing. Creates a new file if it doesn't exist or truncates the file if it exists. |
"a" | Open for appending. Data is added to the end of the file. |
"r+" | Open for both reading and writing. The file must exist. |
"w+" | Open for reading and writing. Creates a new file if it doesn't exist or truncates the file if it exists. |
"a+" | Open for reading and appending. Creates a new file if it doesn't exist. |
Example: Closing a File
fclose(fptr);
Best Practices
- Always check if the file was opened successfully.
- Close files using
fclose()
to free resources. - Use appropriate file modes based on the required operations.
Key Takeaways
- File handling allows data to be stored and retrieved from files.
- Use
FILE *
pointers to manage files. - Properly opening and closing files is crucial for resource management.