42 lines
852 B
C
42 lines
852 B
C
// 自定义二进制文件读取
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
|
|
typedef struct
|
|
{
|
|
int sid;
|
|
char name[32];
|
|
int age;
|
|
char sex[4];
|
|
} STU;
|
|
|
|
int main()
|
|
{
|
|
FILE *f = fopen("d13.txt", "rb");
|
|
if (NULL == f)
|
|
{
|
|
return 1;
|
|
}
|
|
|
|
// 让光标移动到文件尾部
|
|
fseek(f, 0, SEEK_END);
|
|
long file_size = ftell(f); // 获取文件大小
|
|
printf("文件大小: %ld B\n", file_size);
|
|
int stu_num = file_size / sizeof(STU);
|
|
printf("学生数目: %d 位\n", stu_num);
|
|
|
|
fseek(f, 0, SEEK_SET); // 重置光标位置到头
|
|
for (int i = 0; i < stu_num; i++)
|
|
{
|
|
STU *s = calloc(1, sizeof(STU));
|
|
|
|
int fx = fread(s, sizeof(STU), 1, f);
|
|
if (fx != 0)
|
|
printf("%d %s %d %s\n", s->sid, s->name, s->age, s->sex);
|
|
free(s);
|
|
}
|
|
|
|
fclose(f);
|
|
|
|
return 0;
|
|
} |