The fopen() method in C is used to open the specified file.
Let’s take an example to understand the problem
FILE *fopen(filename, mode)
The following are valid modes for opening files using fopen(): 'r', 'w', 'a', 'r ', 'w ', 'a '. For more information please visit C library functions - fopen()
If the file to be opened does not exist in the current directory, it will be created New empty file, using write mode.
If the file to be opened exists in the current directory and is opened using 'w' / 'w ', the contents will be deleted before writing.
Program example illustrating how our solution works
#include <stdio.h> #include <stdlib.h> int main(){ FILE *opFile = fopen("test.txt", "w"); if (opFile == NULL){ puts("Couldn't open file"); exit(0); } else{ fputs("includehelp", opFile); puts("Write operation successful"); fclose(opFile); } return 0; }
Write operation successful
Initial contents of the file - C Programming Language
Contents after append operation - Includes help
The write operation will do its job but delete any content that was present in the file before the write operation was performed . To solve this problem, the C programming language has been updated with two different methods that programmers can use depending on the requirements of the program.
'a' (append) mode - This mode appends new content to the end of what has already been written in the file.
'wx' mode - Returns NULL if the file already exists in the directory.
A program that demonstrates writing to an existing file using 'a' mode
#include <stdio.h> #include <stdlib.h> int main(){ FILE *opFile = fopen("test.txt", "a"); if (opFile == NULL){ puts("Couldn't open file"); exit(0); } else{ fputs("includehelp", opFile); puts("Write operation successful"); fclose(opFile); } return 0; }
Write operation successful
File Initial content − C Programming Language
Content after append operation− C Programming Language includehelp
Use ' Program for writing on existing files in wx' mode
#include <stdio.h> #include <stdlib.h> int main(){ FILE *opFile = fopen("test.txt", "wx"); if (opFile == NULL){ puts("Couldn't open file"); exit(0); } else{ fputs("includehelp", opFile); puts("Write operation successful"); fclose(opFile); } return 0; }
Write operation successful
The above is the detailed content of In C language, use the fopen() function to open an existing file in write mode. For more information, please follow other related articles on the PHP Chinese website!