Various Modes of Accessing a File in C with Example Program
Subject: PPS (Programming for Problem Solving)
Contributed By: Sanjay
Created At: February 3, 2025
Question:
Explain Various Modes of Accessing a File in C with an Example
Explanation Video:
Explanation:
File Access Modes:
In C, a file can be opened in different modes depending on whether we want to read, write, or append data. The fopen() function is used to open a file in a specific mode.
File Access Modes:
Mode | Description |
"r" | Opens a file for reading. File must exist. |
"w" | Opens a file for writing. Creates a new file if it doesn’t exist or overwrites an existing file. |
"a" | Opens a file for appending. If the file doesn’t exist, a new one is created. |
"r+" | Opens a file for reading and writing. File must exist. |
"w+" | Opens a file for reading and writing. Creates a new file if it doesn’t exist, otherwise overwrites it. |
"a+" | Opens a file for reading and appending. If the file doesn’t exist, a new one is created. |
Source Code:
#include <stdio.h>
int main() {
FILE *fp;
fp = fopen("example.txt", "w"); // Open file in write mode
if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}
fprintf(fp, "This is a test file.\n"); // Write data to the file
fclose(fp); // Close the file
printf("File written successfully!\n");
return 0;
}
Output:
File written successfully!
(A file named example.txt is created with the text inside.)