文件读写fopen,fputc,fgetc
#include <stdio.h>
#include <string.h>
void write_file()
{
//1. 以只写方式打开文件,若文件不存在,就创建
FILE *fp = NULL;
fp = fopen("./04.txt","w");
//判断是否打开成功
if (NULL == fp)
{
perror("write_file fopen");
return;
}
//2.使用fputc(),写入文件,一次只能写一个字符,用循环的方式写入字符串
char buf[] = "asffgs";
int n = strlen(buf);
int i;
for (i = 0; i < n; i++)
{
fputc(buf[i],fp);
}
//3.关闭文件
fclose(fp);
fp = NULL;
}
void read_file()
{
//1. 以只读写方式打开文件方式打开文件
FILE *fp = NULL;
fp = fopen("./04.txt","r");
//判断是否打开成功
if (NULL == fp)
{
perror("read_file fopen");
return;
}
//2.使用fgetc(),读入文件,一次只能读一个字符,用循环的方式写入字符串
char ch;
while(1)
{
ch = fgetc(fp);
if(ch == -1)
{
break;
}
printf("ch = %c\n",ch);
}
//3.关闭文件
fclose(fp);
fp = NULL;
}
int main()
{
//write_file();
read_file();
}