fopen() 函数定义在 stdio.h 头文件中。它有助于以给定模式打开参数文件名中指定的文件。
FILE *fopen(const char *filename, const char *mode); #where filename should be a string
fopen() 函数接受两个参数。文件打开模式有以下类型。
| 参数 | 描述 | 必需/可选 |
|---|---|---|
| 文件名 | 要打开的文件名 | 必需 |
| 模式 | 文件访问模式 | 必需 |
fopen() 函数的返回值为文件指针。否则,它返回 NULL,并设置全局变量 errno 以指示错误。
| 输入 | 返回值 |
|---|---|
| 如果执行成功 | 文件指针 |
| 如果执行未成功 | NULL |
#include <stdio.h>
int main () {
FILE * pnt;
pnt = fopen ("myfile.txt", "w+");
fprintf(pnt, "%s %s %s %d", "Hii", "all", "I am", 2000);
fclose(pnt);
return(0);
}
输出
Hii all I am 2000
#include <stdio.h>
int main()
{
// pointer to FILE
FILE* pnt;
pnt = fopen("testfile.txt", "w+");
// adds content to the file
fprintf(pnt, "%s %s %s", "C Program",
"tutorials");
// closes the file
fclose(pnt);
return 0;
}
输出
C Program tutorials