使用结构体整理数据,然后利用二进制存储文件,这样存储的文件类似于数据库,可以实现文件的增删改查
定义结构体
1 | struct student |
创建二进制文件
1 | int main(int argc, char *args[]) |
读取内容
1 | int main() |
替换内容
1 | int main(int argc, char *args[])//替换第3个元素 |
根据ID查找内容
1 | int main()//根据用户输入查找指定ID号的同学 |
插入内容
其主要思想是全部查出,然后添加,再写入1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35void insert(struct student array[], int len)
{
for (int i = len - 1; i >= 2; i--)
{
array[i + 1] = array[i];
}
}
int main()//读取结构体二进制文件所有内容
{
FILE *p = fopen("a.dat", "rb");//只读方式打开二进制文件
if (p == NULL)
{
return 0;
}
struct student *pst = calloc(100, sizeof(struct student));
int index = 0;
while (fread(&pst[index++], sizeof(struct student), 1, p) > 0);//循环读取文件所有内容
insert(pst, index);
pst[2].ID = 100;
strcpy(pst[2].name, "zhao");
for (int i = 0; i < index + 1; i++)
{
printf("ID = %u, name = %s\n", pst[i].ID, pst[i].name);
}
fclose(p);
p = fopen("a.dat", "wb");
if (p == NULL)
{
return 0;
}
fwrite(pst, sizeof(struct student), 11, p);
fclose(p);
free(pst);
return
例子
将txt文本文件转为二进制文件,并随机编号1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
struct student
{
unsigned int ID;
char name[20];
};
void write_dat()
{
srand((unsigned int)time(NULL));//生成一个随机种子
FILE *p1 = fopen("student.txt", "r");//以只读方式打开student.txt文件
FILE *p2 = fopen("student.dat", "wb");//以只读方式打开student.txt文件
while (!feof(p1))
{
struct student st = { 0, "" };
fgets(st.name, sizeof(st.name), p1);
size_t len = strlen(st.name);
if (st.name[len - 1] == '\n')
{
st.name[len - 1] = 0;
}
st.ID = rand();
fwrite(&st, sizeof(struct student), 1, p2);
}
fclose(p1);
fclose(p2);
}
int main()
{
write_dat();
FILE *p = fopen("student.dat", "rb");
if (p == NULL)
{
return 0;
}
struct student st;
while (fread(&st, sizeof(st), 1, p) > 0)
{
printf("ID = %u, name = %s\n", st.ID, st.name);
}
fclose(p);
return 0;
}