C语言 二进制文件-代码记录

一、二进制文件写入

#include <stdio.h>
#include <stdlib.h>
#include "student.h"

void getList(Student aStu[], int number);
int save(Student aStu[], int number);

int main(int argc, char const *argv[]) {
	int number = 0;
	printf("输入学生数量:");
	scanf_s("%d", &number);
	Student* aStu = (Student*)malloc(sizeof(Student) * number);

	getList(aStu, number);
	if (save(aStu, number)) {
		printf("保存成功\n");
	}
	else {
		printf("保存失败\n");
	}

	free(aStu);
	return 0;
}

void getList(Student aStu[], int number) {
	char format[STR_LEN];
	sprintf_s(format, "%%%ds", STR_LEN - 1);

	int i;
	for (i = 0; i < number; i++) {
		printf("第%d个学生:\n", i);
		printf("\t姓名:");
		scanf_s(format, &aStu[i].name, STR_LEN);
		printf("\t性别(0-男,1-女,2-其他):");
		scanf_s("%d", &aStu[i].gender);
		printf("\t年龄:");
		scanf_s("%d", &aStu[i].age);
	}
}

int save(Student aStu[], int number) {
	int ret = -1;
	FILE* fp;
	fopen_s(&fp, "student.data", "w");
	if (fp) {
		ret = fwrite(aStu, sizeof(Student), number, fp);
		fclose(fp);
	}
	return ret == number;
}

student.h

const int STR_LEN = 20;

typedef struct _student {
	char name[STR_LEN];
	int gender;
	int age;
} Student;

二、二进制文件读取

#include <stdio.h>
#include "student.h"

void read(FILE* fp, int index);

int main(int argc, char const* argv[]) {
	FILE* fp;
	fopen_s(&fp, "student.data", "r");
	if (fp) {
		fseek(fp, 0L, SEEK_END);
		long size = ftell(fp);
		int number = size / sizeof(Student);
		int index = 0;
		printf("有%d个数据, 你要看第几个:", number);
		scanf_s("%d", &index);
		read(fp, index - 1);
		fclose(fp);
	}
	return 0;
}

void read(FILE* fp, int index) {
	fseek(fp, index * sizeof(Student), SEEK_SET);
	Student stu;
	if (fread(&stu, sizeof(Student), 1, fp) == 1) {
		printf("第%d个学生:", index + 1);
		printf("\t姓名:%s\n", stu.name);
		printf("\t性别:");
		switch (stu.gender) {
		    case 0: printf("男\n"); break;
			case 1: printf("女\n"); break;
			case 2: printf("其他\n"); break;
		}
		printf("\t年龄:%d\n", stu.age);
	}
}

student.h 同一

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值