文件的写操作(fputc):
#include<stdio.h>
#include<string.h>
int main(void)
{
char buf[128]="";
int i=0;
FILE* fp=fopen("file.txt","w");
if(fp==NULL)
{
perror("fopen");
return 0;
}
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1]=0;
while(buf[i]!='\0')
{
fputc(buf[i],fp);
i++;
}
fclose(fp);
return 0;
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/141df6fa4c9de975651aaa06cd6f8953.png)
文件的读操作(fgetc):
#include<stdio.h>
#include<string.h>
int main(void)
{
char buf[128]="";
int i=0;
FILE* fp=fopen("file.txt","r");
if(fp==NULL)
{
perror("fopen");
return 0;
}
while(1)
{
buf[i]=fgetc(fp);
if(buf[i]==EOF)
break;
i++;
}
printf("%s",buf);
fclose(fp);
return 0;
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/e4177d07d19814f2ec1ca7a170e2e079.png)
将一个文件内容写到另一个文件:
#include<stdio.h>
#include<string.h>
int main()
{
FILE* fp1=fopen("a.txt","r");
FILE* fp2=fopen("b.txt","w");
if(fp1==NULL)
{
perror("fopen");
return 0;
}
if(fp2==NULL)
{
perror("fopen");
return 0;
}
while(1)
{
char ch;
ch=fgetc(fp1);
if(ch==EOF)
break;
fputc(fp2);
}
fclose(fp1);
fclose(fp2);
return 0;