C language open file function use method

  • 2020-04-02 02:12:30
  • OfStack

ANSI C specifies that the file is opened with the function fopen and closed with fclose.

1. The invocation mode is usually:


FILE *fp;
fp=fopen( The file name ,  Open the way );


2. Parameter description:

File names: "myfile.dat", "F:\data\myfile.dat", etc.

Opening mode:
"R "(read only) opens a text file for input
"W "(write only) opens a text file for output
"A "(append) adds data to the end of the file
"Rb "(read only) opens a binary file for input
"Wb "(write only) opens a binary file for output
"R +"(read and write) opens a text file for reading and writing
"W +"(read and write) creates a new text file for read and write
"A +"(read and write) opens a text file for reading and writing
"Rb +"(read and write) opens a binary file for reading and writing
"Wb +"(read and write) creates a new binary for read and write
"Ab +"(read and write) opens a binary file for reading and writing

3. Attention:

(1) for a file opened in "r" mode, data cannot be input to it, and the file already exists, otherwise an error occurs;
(2) if a file is opened in "w" mode, data can only be input to the file. If the opened file does not exist, a new file named with the specified name will be created when the file is opened. If the specified file exists, delete it when it is opened, and then create a new file.
(3) if the function fopen opens the file in error, fopen returns a NULL pointer value;
(4) when the program starts to run, the system automatically opens three standard files: standard input (stdin), standard output (stdout), and standard error output (stderr). If you want to use the input/output terminal, you do not need to open it, you can use it directly, such as fputc(stdout,'a'); Output the character a to the screen.


Related articles: