fputc和fgetc的使用:字符
#include<stdio.h>
#include<string.h>
int main()
{
FILE *f_write = fopen("text1.txt","w");
char form[] = "Hello zhengqian";
int len = strlen(form);
for(int i=0; i<len; i++)
{
fputc(form[i], f_write);
}
fclose(f_write);
FILE *f_read = fopen("text1.txt","r");
char ch;
while((ch = fgetc(f_read))!=EOF){
printf("%c",ch);
}
fclose(f_read);
}
fgets和fputs的使用:行
#include<stdio.h>
#include<string.h>
int main()
{
FILE *f_write = fopen("text2.txt","w");
char *form[] = {
"zhengqian\n",
"keyizaigeiwo\n",
"yicijihuime\n"
};
for(int i=0;i<3;i++)
{
fputs(form[i],f_write);
}
fclose(f_write);
FILE *f_read = fopen("text2.txt","r");
while(!feof(f_read))
{
char buf[1024] = {0};
fgets(buf, 1024, f_read);
printf("%s",buf);
memset(buf,0,1024);
}
fclose(f_read);
}
fwrite和fread的使用:块
#include<stdio.h>
struct Water{
char size[100];
char fish[100];
int num;
};
int main(){
FILE *f_write = fopen("text3.txt","wb");
struct Water water[]{
{"学校","yes",5},
{"路旁","no",0},
{"云里","好多好多鱼",0}
};
for(int i=0; i < 3; i++)
{
fwrite(&water[i], sizeof(struct Water), 1, f_write);
}
fclose(f_write);
struct Water water1[4];
FILE *f_read = fopen("text3.txt","rb");
fread(&water1,sizeof(struct Water),4,f_read);
for(int i=0;i<3;i++)
{
printf("%s %s %d\n",water[i].size,water[i].fish,water[i].num);
}
fclose(f_read);
}
格式化fprintf和fscanf:
#include<stdio.h>
int main(){
int d = 100;
FILE *f_write = fopen("text4.txt","w");
fprintf(f_write, "没想到我还可以这样输入文件,我要输入%d行", d);
fclose(f_write);
FILE *f_read = fopen("text4.txt", "r");
char form[1024] = {0};
fscanf(f_read, "%s", form);
printf("%s", form);
fclose(f_read);
}
随机位置:
#include<stdio.h>
struct Water{
char size[100];
char fish[100];
int num;
};
int main(){
FILE *f_write = fopen("text3.txt","wb");
struct Water water[]{
{"学校","yes",5},
{"路旁","no",0},
{"云里","好多好多鱼",0}
};
for(int i=0; i < 3; i++)
{
fwrite(&water[i], sizeof(struct Water), 1, f_write);
}
fclose(f_write);
struct Water water1;
FILE *f_read = fopen("text3.txt","rb");
fread(&water1,sizeof(struct Water),1,f_read);
printf("%s %s %d\n",water1.size,water1.fish,water1.num);
fseek(f_read,sizeof(struct Water)*2, SEEK_SET); //SEEK_CUR和SEEK_END
fread(&water1,sizeof(struct Water),1,f_read);
printf("%s %s %d\n",water1.size,water1.fish,water1.num);
fclose(f_read);
}