在下面的程序中, 我们将通过键盘键入的字符依次写入demo.txt中.
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fp;/* 定义文件指针fp */
char ch;
if((fp = fopen("C:\\Users\\surface\\Desktop\\demo.txt", "w")) == NULL)/* 以只写的方式打开文件 */
{
/* 打开文件时发生错误 */
printf("Failure to open demo.txt!\n");
exit(0);
}
ch = getchar();
while(ch != '\n')
{
fputc(ch, fp);/* 将刚刚输入的字符写入fp指向的文件中 */
ch = getchar();
}
if(fclose(fp) == 0)
{
/* 文件关闭成功, fclose()返回0 */
printf("Success for writing the string to file demo.txt.\n");
}
else
{
/* 文件关闭失败, fclose()返回EOF(-1) */
exit(0);
}
return 0;
}
[运行结果]
在程序运行前, 指定目录(桌面)下无demo.txt文件, 接下来运行上述程序.
此时切回桌面, 发现demo.txt文件已自动创建.
接着我们打开文件, 查看文件中的内容.
可以发现, 文件中的内容就是我们刚才从键盘输入的内容.
随后我们再次运行上述程序.
在程序运行后, 再次查看demo.txt中的内容.
可以发现, 之前文件中的内容已被清除, 取而代之的是我们刚刚通过键盘键入的信息: 这也是用fopen函数以w模式打开文件的特点.
如果我们希望将demo.txt文件中的内容通过屏幕显示出来, 则需要借助于fgetc函数实现.
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fp;/* 定义文件指针fp */
char ch;
if((fp = fopen("C:\\Users\\surface\\Desktop\\demo1.txt", "r")) == NULL)/* 以只读的方式打开文件 */
{
/* 打开文件时发生错误 */
printf("Failu