Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
fopen() for existing file in write mode in C
The fopen() function in C is used to open files for various operations. When opening an existing file in write mode, it's important to understand how different modes affect the file's content.
Syntax
FILE *fopen(const char *filename, const char *mode);
fopen() for an Existing File in Write Mode
When using fopen() with write mode on an existing file −
- 'w' mode: Creates a new file if it doesn't exist, or truncates (empties) an existing file before writing
- 'w+' mode: Same as 'w' but allows both reading and writing
- 'a' mode: Appends new content to the end of an existing file
- 'wx' mode: Fails if the file already exists (exclusive creation)
Example 1: Write Mode ('w') - Truncates Existing File
This example shows how 'w' mode overwrites an existing file's content −
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *file = fopen("test.txt", "w");
if (file == NULL) {
printf("Could not open file
");
return 1;
}
fprintf(file, "New content replaces old content");
printf("Write operation successful
");
fclose(file);
return 0;
}
Write operation successful
Note: If "test.txt" had previous content like "Old data", it would be completely replaced with "New content replaces old content".
Example 2: Append Mode ('a') - Preserves Existing Content
This example demonstrates how 'a' mode adds content to the end of an existing file −
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *file = fopen("test.txt", "a");
if (file == NULL) {
printf("Could not open file
");
return 1;
}
fprintf(file, " - Appended text");
printf("Append operation successful
");
fclose(file);
return 0;
}
Append operation successful
Note: If "test.txt" contained "Original content", it would become "Original content - Appended text".
Example 3: Exclusive Write Mode ('wx') - Fails if File Exists
This example shows how 'wx' mode prevents overwriting existing files −
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *file = fopen("test.txt", "wx");
if (file == NULL) {
printf("File already exists or could not create file
");
return 1;
}
fprintf(file, "This is a new file");
printf("File created and written successfully
");
fclose(file);
return 0;
}
File already exists or could not create file
Comparison of Write Modes
| Mode | Existing File | Non-existing File | Use Case |
|---|---|---|---|
| 'w' | Truncates content | Creates new file | Complete rewrite |
| 'a' | Preserves and appends | Creates new file | Add to existing content |
| 'wx' | Fails (returns NULL) | Creates new file | Safe file creation |
Conclusion
Choose the appropriate write mode based on your needs: 'w' for complete file replacement, 'a' for appending content, or 'wx' for safe file creation without overwriting existing files.
