A new TXT file can be created using the fopen W method, and the file contents will disappear if the filename exists.
1. fopen function Prototype: FILE * fopen (const char * path,const char * mode);
The first parameter of the fopen function is the file path, and the second argument is open in the following ways:
R opens the file as read-only, and the file must exist.
r+ Open the file as read-write, the file must be present.
rb+ Read and write open a binary file that allows read data.
rw+ Read and write open a text file that allows reading and writing.
W Open Write-only file, if the file exists then the file length is clear to 0, that is, the contents of the file will disappear. If the file does not exist, the file is created.
w+ Open a read-write file, if the file exists then the file length is clear to zero, that is, the contents of the file will disappear. If the file does not exist, the file is created.
A write-only file opens in an additional way. If the file does not exist, the file will be created, and if the file exists, the data written will be added to the end of the file, that is, the original content of the file will be retained. (EOF character reserved)
A + opens readable and writable files in an additional way. If the file does not exist, the file will be created, and if the file exists, the data written will be added to the end of the file, that is, the original content of the file will be retained. (the original EOF character is not preserved)
WB only writes Open or create a new binary file; Only write data is allowed.
wb+ read-write open or create a binary file that allows reading and writing.
wt+ read-write open or create a text file;
at+ Read and write open a text file that allows you to read or append data at the end of the text.
ab+ Read and write open a binary file that allows you to read or append data at the end of the file.
These morphological strings can be added with a B character, such as RB, w+b, or ab+ combinations, and a B character is used to tell the library that the file opened is a binary file, not a plain text file.
Return value: The file pointer to the stream will be returned when the file is opened successfully. Returns null if the file fails to open, and the error code exists in errno.
2. Example:
1#include <stdio.h>2 #defineF_path "D:\\myfile\\file.dat"3 4 CharC;5 6 7 intMain ()8 {9File*fp=null;//need to be awareTenFp=fopen (F_path,"W");//Create a file One if(NULL==FP)return-1;//to return an error code A while(SCANF ("%c", &c)!=eof) fprintf (FP,"%c", c);//read in from the console and in the text output - fclose (FP); -Fp=null;//need to point to null, otherwise it will point to the original open file address the return 0; -}
Create a TXT file and write content