立即学习:https://edu.csdn.net/course/play/10534/380028?utm_source=blogtoedu
学习目标
二进制文件读写:fread(),fwrite()
#include <stdio.h>
// 从数组buffer(缓冲区)中, 写count个大小为size(大小)的对象到stream(流)指定的流. 返回值是已写的对象的数量.
int fwrite(const void *buffer, size_t size, size_t count, FILE *stream);
// 读取[num]个对象(每个对象大小为size(大小)指定的字节数),并把它们替换到由buffer(缓冲区)指定的数组. 数据来自给出的输入流. 函数的返回值是读取的内容数量...
int fread(void *buffer, size_t size, size_t num, FILE *stream);
编程实例
输入N个学生信息,存入文件student.db文件中。
读取文件,输入id查询对应的学生信息输出到屏幕。
#include <stdio.h>
typedef struct {
char name[32];
unsigned age;
long id;
} Student;
void test1(const char *path, const char *w_mode, const char *r_mode) {
FILE* fp = NULL;
unsigned cnt = 0;
Student stu1 = { "WangTeacher", 18, 123456 };
Student stu2 = { 0 };
fp = fopen(path, w_mode);
if (NULL == fp) {
return;
}
cnt = fwrite((void*)(&stu1), sizeof(Student), 1, fp);
fclose(fp);
printf("write cnt = %u\n", cnt);
fp = fopen(path, r_mode);
if (NULL == fp) {
return;
}
cnt = fread((void*)(&stu2), sizeof(Student), 1, fp);
fclose(fp);
printf("read cnt = %u\n", cnt);
printf("stu2 >> %s %u %ld\n", stu2.name, stu2.age, stu2.id);
}
void test2(const char* path, const char* w_mode, const char* r_mode) {
FILE* fp = NULL;
unsigned cnt = 0;
unsigned i = 0;
Student studs[3] = {
{"xiaoming", 7, 1000},
{"zhangsan", 8, 1001},
{"lisi", 6, 1002}
};
Student studs_in[3] = { 0 };
fp = fopen(path, w_mode);
if (NULL == fp) {
return;
}
cnt = fwrite((void*)studs, sizeof(Student), 3, fp);
//fflush(fp);
fclose(fp);
printf("write cnt = %u\n", cnt);
fp = fopen(path, r_mode);
if (NULL == fp) {
return;
}
cnt = fread((void*)studs_in, sizeof(Student), 3, fp);
fclose(fp);
printf("read cnt = %u\n", cnt);
for (i = 0; i < 3; i++) {
printf("%s %u %ld\n", studs_in[i].name, studs_in[i].age, studs_in[i].id);
}
}
int main() {
test1("student1.txt", "w", "r");
printf("================================\n");
test1("student1.bin", "wb", "rb");
printf("================================\n");
test2("student2.txt", "w", "r");
printf("================================\n");
test2("student2.bin", "wb", "rb");
return 0;
}