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
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- How to write your own header file in C?
- Read/Write structure to a file in C
- lseek() in C/C++ to read the alternate nth byte and write it in another file
- Write a C program that displays contents of a given file like 'more' utility in Linux
- C fopen() function with Examples
- C program to copy contents of one file to another file
- Write your own memcpy() and memmove()
- Write a C program that won't compile in C++
- When should we write our own assignment operator in C++?
- When should we write our own copy constructor?
- Write a C macro PRINT(x) which prints x
- Write a program that produces different results in C and C++
- C program to write an image in PGM format
- How to write a running C code without main()?
- Write one line functions for strcat() and strcmp()