In C, fopen() is used to open a file in different modes. To open a file in write mode, “w” is specified. When mode “w” is specified, it creates an empty file for output operations.
What if the file already exists?
If a file with the same name already exists, its contents are discarded and the file is treated as a new empty file. For example, in the following program, if “test.txt” already exists, its contents are removed and “GeeksforGeeks” is written to it.
The above behavior may lead to unexpected results. If programmer’s intention was to create a new file and a file with same name already exists, the existing file’s contents are overwritten.
The latest C standard C11 provides a new mode “x” which is exclusive create-and-open mode. Mode “x” can be used with any “w” specifier, like “wx”, “wbx”. When x is used with w, fopen() returns NULL if file already exists or could not open. Following is modified C11 program that doesn’t overwrite an existing file.
This article is compiled by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- fgets() and gets() in C language
- Basics of File Handling in C
- Read/Write structure to a file in C
- fgetc() and fputc() in C
- fseek() in C/C++ with example
- C Program to print numbers from 1 to N without using semicolon?
- Enumeration (or enum) in C
- To find sum of two numbers without using any operator
- How to deallocate memory without using free() in C?
- Memory Layout of C Programs
- fseek() vs rewind() in C
- EOF, getc() and feof() in C
- Quine - A self-reproducing program
- calloc() versus malloc()
- Understanding "extern" keyword in C