跳到主要内容

C++ fopen() 打开文件函数

fopen() 函数原型

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

fopen() 函数接受两个参数,并返回与由参数 filename 指定的文件相关联的文件流。

它定义在 <cstdio> 头文件中。

文件访问模式的不同类型如下:

文件访问模式解释如果文件存在如果文件不存在
"r"以读取模式打开文件从开始读取错误
"w"以写入模式打开文件清空所有内容创建新文件
"a"以追加模式打开文件从末尾开始写入创建新文件
"r+"以读写模式打开文件从开始读取错误
"w+"以读写模式打开文件清空所有内容创建新文件
"a+"以读写模式打开文件从末尾开始写入创建新文件

fopen() 参数

  • filename:包含要打开的文件名的字符串的指针。
  • mode:指定文件打开模式的字符串的指针。

fopen() 返回值

  • 成功时,fopen() 函数返回控制打开的文件流的 FILE 对象的指针。
  • 失败时返回空指针。

示例 1:使用 fopen() 以写入模式打开文件

#include <cstdio>
#include <cstring>

using namespace std;

int main()
{
int c;
FILE *fp;
fp = fopen("file.txt", "w");
char str[20] = "Hello World!";
if (fp)
{
for(int i=0; i<strlen(str); i++)
putc(str[i],fp);
}
fclose(fp);
}

当你运行程序时,它不会生成任何输出,但会将 "Hello World!" 写入文件 "file.txt"。

示例 2:使用 fopen() 以读取模式打开文件

#include <cstdio>

using namespace std;

int main()
{
int c;
FILE *fp;
fp = fopen("file.txt", "r");
if (fp)
{
while ((c = getc(fp)) != EOF)
putchar(c);
fclose(fp);
}
return 0;
}

当你运行程序时,输出将是[假设与示例 1 中相同的文件]:

Hello World!

示例 3:使用 fopen() 以追加模式打开文件

#include <cstdio>
#include <cstring>

using namespace std;

int main()
{
int c;
FILE *fp;
fp = fopen("file.txt", "a");
char str[20] = "Hello Again.";
if (fp)
{
putc('\n',fp);
for(int i=0; i<strlen(str); i++)
putc(str[i],fp);
}
fclose(fp);
}

当你运行程序时,它不会生成任何输出,但会在新的一行中将 "Hello Again" 追加到文件 "file.txt" 中。