练习使用 (1) fopen (2) fclose (3) fread (4) fwrite
FILE *p_file = fopen("文件名","r+") r,w,b,+
fclose(" p_file ");
fread(数组首地址,sizeof(变量类型) , 读取数量,文件指针 );
返回值是读取到的数据。
fwrite(数组首地址,sizeof(变量类型) , 读取数量,文件指针 );
返回值还是读取的数据。
下面的代码是将从控制台中输入的 id,age , salary
#include <stdio.h>
int main()
{
int id,age;
float salary;
char choice;
FILE *p_file = fopen("record.bin","ab");
if(p_file){
do{
printf("please input your id,age and salary: ");
scanf("%d%d%f",&id,&age,&salary);
fwrite(&id,sizeof(id),1,p_file);
fwrite(&age,sizeof(age),1,p_file);
fwrite(&salary,sizeof(salary),1,p_file);
scanf("%*[^\n]");
scanf("%*c");
printf("Do you want to input another piece of information ?");
printf(" Press Y or N\n"); // 输入N就退出
scanf("%c",&choice);
if(choice == 'n' || choice == 'N'){
break;
}
}while(1);
}
fclose(p_file);
p_file = NULL;
return 0;
}