先简单介绍几个函数:
fopen(“1.txt”,“w”)意为file open,第一个参数是文件名,第二个参数是打开方式,w是只写,r是只读,a是追加,返回该文件的指针
fclose(fp)意为file close,参数为文件指针,成功关闭返回0,否则返回EOF,也就是-1
fgetc(fp)意为file get character,参数为文件指针,成功则返回所读字符,失败返回EOF
fputc(ch,fp)意为file put character,第一个参数为字符,第二个参数是被写入的文件的指针,成功则返回输出的字符,失败返回EOF
fgets(str,n,fp)意为file get string,第一个参数是字符数组名,第二个参数是返回字符的个数减1(补’\0’),第三个参数是所读文件的指针,读成功返回地址,失败返回NULL
fputs(str,fp)意为file put string,第一个参数是字符数组名,第二个参数是文件指针,输出成功,返回0,否则返回非0值
直接上代码:
1.向文件中输入字符:
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE*fp;//声明文件指针
fp=fopen("3.txt","w");//打开文件3.txt,自动创建文件3.txt同时覆盖该文件夹中的同名文件
if(fp==NULL){//打开失败
printf("can not open file");
exit(0);//退出
}
printf("now getchar:");
char ch=getchar();//先读一个
while(ch!='#'){//结束符#
fputc(ch,fp);//向文件中输出字符ch
putchar(ch);//输出到屏幕上
ch=getchar();//从屏幕上读字符
}
fclose(fp);//关闭文件
}
2.对文件字符的读写
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE*in,*out;
in=fopen("0.txt","r");//只读:若文件不存在则出错,返回空指针
out=fopen("1.txt","w");
if(in==NULL||out==NULL)
{
printf("can not open file");
exit(0);
}
char ch=fgetc(in);
while(!feof(in))//此函数用来判断是否是文件结束,是返回1,不是返回0
{
fputc(ch,out);//把ch输出到out里
putchar(ch);
ch=fgetc(in);//从in中读字符
}
fclose(in);
fclose(out);
}
3.对文件字符串的读写
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
int main()
{
FILE*fp=fopen("4.txt","w");
char a[20]="file",b[20]={0};
if(fp==NULL){
printf("can not open file");
exit(0);
}
fputs(a,fp);//把字符串a输出到fp中
printf("%s\n",a);
fclose(fp);
FILE*fp2=fopen("4.txt","r");
if(fp2==NULL){
printf("can not open file");
exit(0);
}
fgets(b,10 ,fp);//从fp中读9个字符
printf("%s",b);
fclose(fp2);
return 0;
}
总结:显然如果整体读取,用fgets和fputs更简单而且更快