C语言文件读写例题,fgetc,fputc,fgets,fputs,fread,fwrite,fscanf,fprintf

int main()
{
	FILE *fp;
	char ch;
	char str[1024],st[11];//str[]用来读取文件中的内容,st[]用来输入内容到文件
	
	fp=fopen("dest.txt","w+");
	//fgetc与fputc使用
	printf("fputc输入文件,请输入:");
	ch=getchar();
	while(ch!='\n')
	{
		fputc(ch,fp);
		ch=getchar();
	}
	rewind(fp);
	printf("\nfgetc输出文件,输出为:");
	ch=fgetc(fp);
	while(ch!=EOF)
	{
		putchar(ch);
		ch=fgetc(fp);
	}
	fclose(fp);


	//fgets与fputs
	if((fp=fopen("dest.txt","r+"))==NULL)
	{
		printf("error\n");
		exit(-1);
	}
	printf("\n\nfgets读取文件中的内容:");
	fgets(str,1024,fp);
	printf("%s\n",str);
	fclose(fp);
	if((fp=fopen("dest.txt","a"))==NULL)
	{
		printf("error\n");
		exit(1);
	}
	printf("\n使用fputs追加内容:");
	scanf("%s",st);
	fputs(st,fp);//文件写入成功!
	fclose(fp);
	fp=fopen("dest.txt","r");
	printf("\n使用fgets把内容完全读完!:\n");
	while(fgets(str,5,fp)!=NULL)
	{
		printf("%s",str);
	}
	fclose(fp);


	//fread与fwrite
	fp=fopen("dest.txt","w");
	printf("\n\n使用fwrite写到文件:");
	scanf("%s",str);
	fwrite(str,sizeof(int),1,fp);
	fclose(fp);
	fp=fopen("dest.txt","r");
	printf("\n使用fread读文件到屏幕:");
	fread(st,sizeof(int),1,fp);
	printf("%s",st);
	fclose(fp);


	//fscanf与fprintf
	fp=fopen("dest.txt","w");
	printf("\n\nfprintf读内容到文件:");
	scanf("%s",st);
	fprintf(fp,"%s",st);
	fclose(fp);

	fp=fopen("dest.txt","r");
	printf("\nfscanf写文件到str:");
	fscanf(fp,"%s",str);
	printf("%s\n",str);
	fclose(fp);

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值