How to use the fopen function in the C language?
The fopen function is used to open a file and returns a pointer to that file.
Function prototype:
FILE* fopen(const char *filename, const char *mode);
Description of parameters:
- File name: the name of the file that you want to open, which can be either an absolute path or a relative path.
- mode: The mode for opening a file can be one of the following:
“r”: Opens the file in read-only mode.
“w”: Opens the file in write mode, clears the file content if the file already exists, and creates a new file if it doesn’t exist.
“a”: Opens the file in append mode, appends content at the end of the file if it already exists, and creates a new file if it doesn’t exist.
“rb”: Opens the file in binary read-only mode.
“wb”: Opens the file in binary write mode.
“ab”: Opens the file in binary append mode.
For more modes, please refer to the C language documentation.
Return value:
- If the file is successfully opened, a pointer to the FILE structure is returned, which can be used for subsequent file operations.
- If the file fails to open, return NULL.
For example, the following code demonstrates how to use the fopen function to open a file and read its contents:
#include <stdio.h>
int main() {
FILE *fp;
char ch;
// 打开文件
fp = fopen("test.txt", "r");
if (fp == NULL) {
printf("文件打开失败\n");
return 1;
}
// 读取文件内容
while ((ch = fgetc(fp)) != EOF) {
putchar(ch);
}
// 关闭文件
fclose(fp);
return 0;
}