Detailed usage of fopen in C language

fopen is a function used to open files in C language, and its prototype is:

FILE *fopen(const char *filename, const char *mode);

Among them, filename is the name of the file to be opened, and mode is the mode of opening the file. The fopen function returns a pointer to the FILE type, which points to the opened file.

The mode parameter of the fopen function has the following types:

  • "r": Open the file as read-only. The file must exist, otherwise the open will fail.

  • "w": Open the file for writing. If the file does not exist, create the file; if the file already exists, empty the file content.

  • "a": Open the file for appending. If the file does not exist, create the file; if the file already exists, append the content at the end of the file.

  • "r+": Open the file for reading and writing. The file must exist, otherwise the open will fail.

  • "w+": Open the file for reading and writing. If the file does not exist, create the file; if the file already exists, empty the file content.

  • "a+": Open the file for reading and writing. If the file does not exist, create the file; if the file already exists, append the content at the end of the file.

In addition to the above six modes, you can also add a "b" character to the mode string, which means to open the file in binary mode. For example, "rb" means to open the binary file read-only.



After the fopen function successfully opens the file, you can use the fclose function to close the file, for example:

FILE *fp = fopen("file.txt", "r");
// 使用文件
fclose(fp);


When using files, you can use functions such as fread, fwrite, fscanf, and fprintf to perform read and write operations. For example:

FILE *fp = fopen("file.txt", "w");
fprintf(fp, "Hello, world!\n");
fclose(fp);

The above code writes the string "Hello, world!\n" to the file.



It should be noted that when using a file, you should first check whether the file is successfully opened. If the file fails to open, the fopen function will return a NULL pointer. For example:

FILE *fp = fopen("file.txt", "r");
if (fp == NULL) {
    printf("Failed to open file.\n");
    return 1;
}


In addition, you should also pay attention to the closing of the file. If a program does not close the file after using it, it may result in the file being occupied and inaccessible by other programs. Therefore, you should close the file in time after using it, for example:

FILE *fp = fopen("file.txt", "r");
// 使用文件
fclose(fp);​

In short, the fopen function is an important function used to open files in C language. By specifying different modes, the read and write operations on files can be realized. When using files, you should pay attention to check whether the file is successfully opened, and close the file in time.

Guess you like

Origin blog.csdn.net/qq_50942093/article/details/130166664