c文件操作之fopen、fclose、fread、fwrite及相关fseek、ftell、rewind例子


在wchar.h中,可以看到

#ifndef _FILE_DEFINED

  struct _iobuf {
    char *_ptr;
    int _cnt;
    char *_base;
    int _flag;
    int _file;
    int _charbuf;
    int _bufsiz;
    char *_tmpfname;
  };
  typedef struct _iobuf FILE;
#define _FILE_DEFINED

#endif

可知,FILE是一个typedef声明掩盖住的一个结构体类型。


二、fread、fwrite

1.fwrite,由单纯的字符串数组中获取数据


#include <stdio.h>
int main()
{
	FILE *pFile;
	char buffer[] = {'x','y','z'};
	pFile = fopen("myfile.bin","wb");
	fwrite(buffer,sizeof(buffer),1,pFile);//将buffer内容写入到文件中。每次写入buffer数组长度,总共写入一次 
	fclose(pFile);
	return 0;
} 

2.fwrite,由结构体传数据到文件

#include<stdio.h>
#include "string.h"
#define SIZE 1
#define max_buf 1000
typedef struct
{
	char name[10];
	int num;
	int age;
	char addr[15];
} student;

student  stu[SIZE];

void  save()
{
	FILE * fp;
	int i;
	char outbuf[max_buf];//用于缓存所有字符型数据 
	char tempbuf[20];//将非字符型的转换成字符型的缓存数组 
	 
	
	if ((fp=fopen("dat.txt","w")) == NULL)
	{
		printf("无法打开此文件");
		return;
	}
	//直接用fwrite会出现乱码
//	for (i = 0; i< SIZE; i++)
//	{
//		 
//		if (fwrite(&stu[i],sizeof(student),1,fp) != 1)
//			printf("文件写入错误\n");
//	 
//	}
	//方式一  用fprintf格式化输出
		for (i = 0; i< SIZE; i++)
	{
		fprintf(fp,"%s\n",stu[i].name);
		fprintf(fp,"%d\n",stu[i].num);
		fprintf(fp,"%d\n",stu[i].age);
		fprintf(fp,"%s\n",stu[i].addr);
	}
	//方法二、用fwrite,但得把非字符型转化成字符型 
//		memset(outbuf,0,max_buf);
//		for (i = 0; i< SIZE; i++)
//	{
//		sprintf(tempbuf,"%s\n",stu[i].name);
//		printf("tembuf = %s\n",tempbuf);
//		strcat(outbuf,tempbuf); 
//		
//		sprintf(tempbuf,"%d\n",stu[i].num);
//		printf
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值