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);
}
运行程序时,它不会生成任何输出,但会在文件“file.txt”的末尾添加换行符“Hello Again”。
另请阅读