fopen() Function
The fopen()
function in C opens a file and associates it with a stream, enabling file operations such as reading, writing, and appending. This function provides flexible access to files by supporting various modes that dictate how the file is opened and manipulated.
Syntax of fopen()
FILE *fopen(const char *filename, const char *mode);
Parameters
Parameter | Description |
---|---|
filename | A C string containing the name (and optionally the path) of the file to be opened. |
mode | A C string specifying the file access mode. Common modes include:
"r" – read (file must exist),
"w" – write (creates or truncates file),
"a" – append (writes at end of file),
"r+" – read/update (file must exist),
"w+" – write/update (creates or truncates file),
"a+" – append/update (creates file if not exists).
|
It is important to choose the correct mode to ensure the desired file operations are permitted and to avoid unintended data loss. For binary files, add a "b"
to the mode string (e.g., "rb"
, "wb"
, etc.).
Return Value
If the file is successfully opened, fopen()
returns a pointer to a FILE
object that can be used in subsequent operations. If the file cannot be opened, it returns a null pointer and typically sets the errno
variable to indicate the error.
Examples for fopen()
Example 1: Opening a File in Read Mode (“r”)
This example demonstrates how to open an existing file for reading. The program attempts to open “example.txt” and read its content.
Program
#include <stdio.h>
int main() {
FILE *fp = fopen("example.txt", "r");
char ch;
if (fp == NULL) {
printf("Error: Could not open file for reading.\n");
return 1;
}
// Read and display content
while ((ch = fgetc(fp)) != EOF) {
putchar(ch);
}
fclose(fp);
return 0;
}
Explanation:
- The file “example.txt” is opened in read mode using
fopen("example.txt", "r")
. - If the file cannot be opened, an error message is printed.
- If successful, the program reads the file character by character using
fgetc()
and displays the content. - The file is closed using
fclose()
after reading.
Program Output:
[Content of example.txt]
Example 2: Creating and Writing to a File in Write Mode (“w”)
This example demonstrates how to open a file in write mode. The file “output.txt” is created (or truncated if it already exists) and new content is written to it.
Program
#include <stdio.h>
int main() {
FILE *fp = fopen("output.txt", "w");
if (fp == NULL) {
printf("Error: Could not open file for writing.\n");
return 1;
}
fprintf(fp, "This is a test in write mode.\n");
fclose(fp);
printf("File 'output.txt' created and written successfully.\n");
return 0;
}
Explanation:
- The file “output.txt” is opened in write mode using
fopen("output.txt", "w")
. If the file exists, its content is cleared. - The program writes a line of text to the file using
fprintf()
. - The file is then closed with
fclose()
. - A confirmation message is printed to indicate the successful operation.
Program Output:
File 'output.txt' created and written successfully.
Example 3: Appending Data to a File in Append Mode (“a”)
This example demonstrates how to open a file in append mode. The program adds new content to the end of “append.txt” without altering its existing content.
Program
#include <stdio.h>
int main() {
FILE *fp = fopen("append.txt", "a");
if (fp == NULL) {
printf("Error: Could not open file for appending.\n");
return 1;
}
fprintf(fp, "Appending new line.\n");
fclose(fp);
printf("Data appended to 'append.txt' successfully.\n");
return 0;
}
Explanation:
- The file “append.txt” is opened in append mode using
fopen("append.txt", "a")
. - If the file does not exist, it is created.
- The program writes a new line to the end of the file using
fprintf()
. - The file is closed with
fclose()
, and a success message is printed.
Program Output:
Data appended to 'append.txt' successfully.
Example 4: Reading and Updating a File in Read/Update Mode (“r+”)
This example demonstrates how to open an existing file for both reading and updating. The file “update.txt” is first read and then updated with new content.
Program
#include <stdio.h>
int main() {
FILE *fp = fopen("update.txt", "r+");
char buffer[100];
if (fp == NULL) {
printf("Error: Could not open file for reading/updating.\n");
return 1;
}
// Read and display initial content
while (fgets(buffer, sizeof(buffer), fp) != NULL) {
printf("%s", buffer);
}
// Reposition to beginning and update content
rewind(fp);
fprintf(fp, "Updated content.\n");
fclose(fp);
printf("\nFile 'update.txt' read and updated successfully.\n");
return 0;
}
Explanation:
- The file “update.txt” is opened in read/update mode with
fopen("update.txt", "r+")
. - The program reads and displays its initial content using
fgets()
. - It then repositions to the beginning using
rewind()
and writes new content usingfprintf()
. - The file is closed and a confirmation message is printed.
Program Output:
[Initial content of update.txt, followed by:]
Updated content.
File 'update.txt' read and updated successfully.