1. 写入文件
fputc函数
与fgetc()
函数相反,fputc()
函数用于向文件中写入一个字符。
fputc
的函数原型:
int fputc (int character, FILE * stream);
输入:
int character
写入文件的字符
FILE * stream
文件结构指针
输出:
如果写入成功,返回刚刚写入的字符。如果文件结尾或失败,则返回EOF
。并且,ferror可以检测到文件读写出错。
使用指针p
的移动遍历"HelloWorld\n"
字符串,直到指针指向字符为'\0'
为止。遍历结束前的字符,均被fputc
函数写入到文件当中。
请注意,目前函数fopen
使用的是"w"
写入模式。因此,文件将清空原内容再写入。
#include <stdio.h>
int main()
{
FILE* pFile = fopen("data.txt", "w"); // 写模式
if (pFile == NULL)
{
return -1;
}
char str[] = "HelloWorld\n";
char *p = str;
while(*p != '\0')
{
// 向文件中写入一个字符
fputc(*p, pFile);
p++;
}
fclose(pFile);
return 0;
}
程序运行完成后,将会在文件中看到一串字符"HelloWorld"
并换行。
如果,现在想在第一行后,再增加更多的"HelloWorld"
,再运行一遍上面的程序可以吗?别忘了,若函数fopen
使用的是"w"
写入模式,文件将清空原内容再写入。现在,我们需要保留原有内容,继续在文件尾部添加新内容。这时候,需要使用追加模式"a"
。字符a
为单词追加append
的首字母。
#include <stdio.h>
int main()
{
FILE* pFile = fopen("data.txt", "a"); // 追加模式
if (pFile == NULL)
{
return -1;
}
char str[] = "HelloWorld\n";
char *p = str;
while(*p != '\0')
{
fputc(*p, pFile);
p++;
}
fclose(pFile);
return 0;
}
多运行几次,可以发现,文件中有了多行HelloWorld
了。
注意,代码从未将'\0'
写入过文件,文件中的每一行都是由换行分隔。且'\0'
也不标记文件结尾。文件是否结尾可以通过文件操作函数返回值和feof
函数的返回值判断。
fputs函数
fputs()
函数用于向文件中写入一串字符串。
fputs
的函数原型:
int fputs (const char * str, FILE * stream);
输入:
const char * str
待写入文件的字符串
FILE * stream
文件结构指针
输出:
如果写入成功,返回一个非负值。如果写入失败,则返回EOF
。并且,ferror
可以检测到文件读写出错。
#include <stdio.h>
int main()
{
FILE* pFile = fopen("data.txt", "w"); // 写模式
if (pFile == NULL)
{
return -1;
}
char str[] = "Have a good time\n";
for(int i = 0 ; i < 5; i ++)
{
// 向文件中写入5行"Have a good time\n"
fputs(str, pFile);
}
fclose(pFile);
return 0;
}
由于用fopen
函数打开文件时,使用了"w"
写模式。因此,文件原内容将清空,写入5行"Have a good time\n"
。
把上面的代码,在关闭文件前,先暂停一下。
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE* pFile = fopen("data.txt", "w"); // 写模式
if (pFile == NULL)
{
return -1;
}
char str[] = "Have a good time\n";
for(int i = 0 ; i < 5; i ++)
{
fputs(str, pFile);
}
// 关闭文件前,先暂停一下
system("pause");
fclose(pFile);
return 0;
}
虽然在运行到暂停时,向文件中写入数据的fputs(str, pFile)
语句已经运行过了。但是,现在打开文件,文件内没有任何内容。
我们按任意键让暂停继续。程序结束后,文件内出现了内容。
为什么会出现这样的现象呢?