在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