#include <stdio.h>
#include <string.h>
struct student
{
char name[10];
int age;
};
int main05(void)
{
struct student st[5] = { 0 };
int i;
for(i = 0; i < 5; i++)
{
printf("please name:");
scanf("%s", st[i].name);
printf("please age:");
scanf("%d", &st[i].age);
}
FILE *p = fopen("D:\\temp\\a.dat", "wb");
fwrite(st, sizeof(struct student), 10, p);
fclose(p);
return 0;
}
int main02()
{
struct student st = { 0 };
FILE *p = fopen("D:\\temp\\a.dat", "rb");
//fseek(p, sizeof(struct student) * 2, SEEK_SET);//从文件开始位置向后偏移结构student这么多的字节
memset(&st, 0, sizeof(struct student));
fread(&st, sizeof(struct student), 1, p);
printf("name = %s, age = %d\n", st.name, st.age);
fseek(p, 0 - sizeof(struct student), SEEK_CUR);//从当前位置往回偏移
memset(&st, 0, sizeof(struct student));
fread(&st, sizeof(struct student), 1, p);
printf("name = %s, age = %d\n", st.name, st.age);
fseek(p, 0 - sizeof(struct student), SEEK_END);//从文件结尾位置往回偏移
memset(&st, 0, sizeof(struct student));
fread(&st, sizeof(struct student), 1, p);
printf("name = %s, age = %d\n", st.name, st.age);
// while(1)
// {
// memset(&st, 0, sizeof(struct student));
// if (fread(&st, sizeof(struct student), 1, p) == 0)
// break;
// printf("name = %s, age = %d\n", st.name, st.age);
// }
fclose(p);
return 0;
}
int main03()
{
FILE *p = fopen("D:\\temp\\a.txt", "rb");
fseek(p, 2, SEEK_SET);
char buf[100] = { 0 };
fgets(buf, sizeof(buf), p);
printf("buf = %s\n", buf);
fgets(buf, sizeof(buf), p);
printf("ftell = %d\n", ftell(p));
fclose(p);
return 0;
}
int main04()
{
FILE *p = fopen("D:\\temp\\a.txt", "rb");
while(!feof(p))
{
fseek(p, 0, SEEK_END);//偏移到文件最后
char buf[100] = { 0 };
fgets(buf, sizeof(buf), p);
printf("buf = %s", buf);
}
fclose(p);
return 0;
}
void swap(struct student *a, struct student *b)
{
struct student tmp = *a;
*a = *b;
*b = tmp;
}
void bubble(struct student *p, int n)
{
int i;
int j;
for(i = 0; i < n; i++)
{
for(j = 1; j < n - i; j++)
{
if (p[j - 1].age > p[j].age)
{
swap(&p[j - 1], &p[j]);
}
}
}
}
int main(void)
{
struct student st[5] = { 0 };
FILE *p = fopen("D:\\temp\\a.dat", "rb");
int i;
// for(i = 0; i < 5; i++)//读取文件的代码
// {
// fread(&st[i], sizeof(struct student), 1, p);
// }
fread(st, sizeof(struct student), 5, p);
fclose(p);
bubble(st, 5);
// for(i = 0; i < 5; i++)
// {
// printf("name = %s, age = %d\n", st[i].name, st[i].age);
// }
p = fopen("D:\\temp\\b.dat", "wb");
// for(i = 0; i < 5; i++)
// {
// fwrite(&st[i], sizeof(struct student), 1, p);
// }
fwrite(st, sizeof(struct student), 5, p);
fclose(p);
return 0;
}
结构体二进制读写和排序
最新推荐文章于 2021-05-23 03:09:57 发布