文本文件和二进制的区别:
存储的格式不同:文本文件只能存储文本。
计算机内码概念:文本符号在计算机内部的编码(计算机内部只能存储数字0101001....,所以所有符号都要编码)
二进制读写函数格式:
size_t fread(void *ptr, size_t size, size_t n, FILE *fp);
void *ptr //读取内容放的位置指针
size_t size //读取的块大小
size_t n //读取的个数
FILE *fp //读取的文件指针
size_t fwrite(const void *ptr, size_t size, size_t n, FILE *fp);
void *ptr //写文件的内容的位置指针
size_t size //写的块大小
size_t n //写的个数
FILE *fp //要写的文件指针
注意事项:
文件写完后,文件指针指向文件末尾,如果这时候读,读不出来内容。
解决办法:移动指针到文件头;关闭文件,重新打开
#include
#include
int main(int argc,char *argv[]){
FILE *fp;
char *buff;
size_t ret;
fp=fopen("1.txt","r");
if(fp==NULL){
perror("fopen");
return 0;
}
buff=(char*)malloc(100);
if(buff==NULL){
return 0;
}
ret = fread(buff,10,1,fp);
if(ret==-1){
perror("fread");
goto end;
}
printf("buf=%s\n",buff);
end:
free(buff);
fclose(fp);
}
#include
#include
#include
struct student{
char name[16];
int age;
char sex[8];
};
int main(int argc,char *argv[]){
FILE *fp;
size_t ret;
struct student stu2;
fp=fopen("1.bin","r");
if(fp==NULL){
perror("fopen");
return 0;
}
ret = fread(&stu2,sizeof(stu2),1,fp);
if(ret ==-1){
perror("fread");
goto end;
}
printf("name=%s,age=%d,sex=%s\n",stu2.name,stu2.age,stu2.sex);
end:
fclose(fp);
}
使用标准IO写2个学生的结构体数据到文件。
#include
#include
#include
struct student{
char name[20];
int age;
char sex[10];
};
int main(){
FILE *fp;
size_t ret;
struct student stu;
struct student stu1;
struct student stu2;
fp = fopen("1.bin","w");
if (fp == NULL){
perror("fopen");
return 0;
}
strcpy(stu1.name,"张三");
stu1.age = 16;
strcpy(stu1.sex,"男");
strcpy(stu2.name,"李四");
stu2.age = 15;
strcpy(stu2.sex,"女");
ret = fwrite(&stu,sizeof(stu),2,fp);
if(ret == -1){
perror("fwrite");
goto end;
}else{
printf("fwrite suceese\n");
}
fclose(fp);
fp = fopen("1.bin","r");
if (fp == NULL){
perror("fopen");
return 0;
}
ret = fread(&stu,sizeof(stu),2,fp);
if(ret == -1){
perror("fread");
goto end;
}
printf("name1=%s,age1=%d,sex1=%s\n",stu1.name,stu1.age,stu1.sex);
printf("name2=%s,age2=%d,sex2=%s\n",stu2.name,stu2.age,stu2.sex);
end:
fclose(fp);
return 0;
}
运行结果: