二进制读写
文本文件和二进制的区别:
存储的格式不同:文本文件只能存储文本。
计算机内码概念:文本符号在计算机内部的编码(计算机内部只能存储数字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 <stdio.h>
#include <stdlib.h>
#include <string.h>
struct student{
char name[16];
int age;
char sex[8];
};
int main(int argc,char *argv[]){
FILE *fp;
size_t ret;
struct student stu;
struct student stu2;
fp=fopen("1.bin","w");
if(fp==NULL){
perror("fopen");
return 0;
}
strcpy(stu.name,"zhangsan");
stu.age = 49;
strcpy(stu.sex,"male");
ret = fwrite(&stu,sizeof(stu),1,fp);
if(ret ==-1){
perror("fwrite");
goto end;
}else{
printf("write struct student success!\n");
}
fclose(fp);
fp=fopen("1.bin","r");
if(fp==NULL){
perror("fopen");
return 0;
}
ret = fread(&stu2,sizeof(stu),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);
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
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);
}
#include <stdio.h>
#include <stdlib.h>
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);
}