C语言读写文件系列

4 篇文章 0 订阅
3 篇文章 0 订阅

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);
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值