C语言fwrite函数了解

fwrite()函数----write data to a stream

原型:

size_t fwrite(const void* buffer, size_t size, size_t count, FILE* stream);

注意:这个函数以二进制形式对文件进行操作,不局限于文本文件

demo:

#include <stdio.h>
#include <process.h>
typedef struct 
{
	int i;
	char ch;
}mystruct;
int main()
{
	FILE *stream;
	mystruct s;
    /*wb只写打开或新建一个二进制文件;只允许写数据。*/
	if ((stream=fopen("test.$$$","wb"))==NULL)
	{
		fprintf(stderr,"cannot open output file.\n");
		return 1;
	}
	s.i=0;
	s.ch='A';
	fwrite(&s,sizeof(s),1,stream);
	fclose(stream);
	stream=NULL;
	system("pause");
	return 0;
}

demo2:

#include <stdio.h>
int main()
{
	FILE *pFile=NULL;
	char buffer[]={'x','y','z'};
	pFile=fopen("myfile.bin","wb");
	fwrite(buffer,sizeof(buffer),1,pFile);
	fclose(pFile);
	system("pause");
	return 0;
}

demo3:

#include <stdio.h>
#include <process.h>
int main()
{
	FILE *fp=NULL;
	char msg[]="file content";
	char buf[20];
	fp=fopen("c:\\a.txt","w+");    //二级目录会不成功
	if (NULL==fp)
	{
		printf("The file doesn't exist!\n");
		getchar();
		getchar();
		return -1;
	}
	fwrite(msg,strlen(msg),1,fp);   //把字符串内容写入到文件
	fseek(fp,0,SEEK_SET);           //定位文件指针到文件首位置
	fread(buf,strlen(msg),1,fp);    //把文件读入到缓存
	buf[strlen(msg)]='\0';          //删除缓存内多余空间
	printf("buf=%s\n",buf);
	printf("strlen(buf) = %d\n",strlen(buf));
	system("pause");
	return 0;
}


  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值