C语言 读写内存数据



在下面的例子中,我使用一个占用32字节内存的结构体,并将其写入文件并将其读入-即将数据序列化为二进制格式:

#include <stdio.h>
typedef struct _Person {
char   name[20];
int    age;
double weight;
} Person;
int main(void)
{
Person tom = (Person) {.name="Tom", .age=20, .weight=125.0};
// write the struct to a binary file
FILE *fout = fopen("person.b", "wb");
fwrite(&tom, sizeof tom, 1, fout);
fclose(fout);
// read the binary data and set the person to that
Person unknown;
FILE *fin = fopen("person.b", "rb");
fread(&unknown, sizeof unknown, 1, fin);
fclose(fin);
// confirm all looks ok
printf("{name=%s, age=%d, weight=%f}", unknown.name, unknown.age, unknown.weight);
}

请注意,这些都是堆栈上的值,不涉及指针/间接。如何将数据序列化到文件中,例如,可能涉及多个指针,多个变量可能指向相同的内存位置,等等。这是协议缓冲区所做的吗?

你想要一个二进制文件。很久以前我就是这么做的。它很好。当你搬到另一个平台或地方时,它就会破裂。我用老方法教,因为这是一个很好的开始。更新的方法现在很受欢迎,因为它们在更换平台或比特时仍然有效。

当将记录写入文件时,我会使用这样的结构体:

typedef struct _Person {
char   name[20];
int    age;
double weight;
} Person;
typedef struct _Thing {
char name[20];
};
typedef struct _Owner {
int personId;
int thingId;
} Owner;

查看Owner结构体如何有Id个成员。这些只是其他结构数组的下标。

这些可以一个接一个地写入到文件中,通常以一个直接写入的整数作为前缀,表示每种记录的数量。阅读器只是分配一个结构体数组,malloc足够大,可以容纳它们。当我们在内存中添加更多项目时,我们使用realloc调整数组的大小。我们还可以(也应该)标记为删除(例如通过将name的第一个字符设置为0)并在以后重用该记录。

作者看起来像这样:

void writeall(FILE *h, Person *allPeople, int nPeople, Thing *allThings, int nThings, Owner *allOwners, int nOwners)
{
// Error checking omitted for brevity
fwrite(&nPeople, sizeof(nPeople), 1, h);
fwrite(allPeople, sizeof(*allPeople), nPeople, h);
fwrite(&nThings, sizeof(nThings), 1, h);
fwrite(allThings, sizeof(*allThings), nThings, h);
fwrite(&nOwners, sizeof(nOwners), 1, h);
fwrite(allOwners, sizeof(*allOwners), nOwners, h);
}

阅读器看起来像这样:

int writeall(FILE *h, Person **allPeople, int *nPeople, int *aPeople, Thing **allThings, int *nThings, int *aThings, Owner **allOwners, int *nOwners, int *aOwners)
{
*aPeople = 0; // Don't crash on bad read
*aThigns = 0;
*aOwners = 0;
*allPeople = NULL;
*allThings = NULL;
*allOwners = NULL;
if (1 != fread(nPeople, sizeof(*nPeople), 1, h)) return 0;
*allPeople = malloc(sizeof(**allPeople) * *nPeople);
if (!allPeople) return 0; // OOM
*aPeople = *nPeople;
if (*nPeople != fread(*allPeople, sizeof(**allPeople), nPeople, h)) return 0;
if (1 != fread(nThings, sizeof(*nThings), 1, h)) return 0;
*allThings = malloc(sizeof(**allThings) * *nThings);
if (!allThings) return 0; // OOM
*aThings = *nThings;
if (*nThings != fread(*allThings, sizeof(**allThings), nThings, h)) return 0;
if (1 != fread(nOwners, sizeof(*nOwners), 1, h)) return 0;
*allOwners = malloc(sizeof(**allOwners) * *nOwners);
if (!allOwners) return 0; // OOM
*aOwners = *nOwners;
if (*nOwners != fread(*allOwners, sizeof(**allOwners), nOwners, h)) return 0;
return 1;
}

有一种古老的技术可以将堆竞技场直接写入磁盘,然后再将其读取回来。我建议永远不要使用它,也不要在磁盘上存储指针。这是安全噩梦。

当内存很便宜的时候,我会讨论如何使用块分配和链接块来动态更新部分磁盘上的记录;但是现在对于你们在这一层会遇到的问题,我说不用麻烦了,只要把所有的东西读到RAM里,然后再写出来。最后你将学习数据库,它会帮你处理这些事情。

最新更新