C fwrite() 不会保存文件中的所有数据

C fwrite() won't save every data in the file

int nrAnimals = 0;
ANIMAL animals[10];
addTestData(animals, &nrAnimals);

static void addTestData(ANIMAL* animals, int* nrAnimals)
{
ANIMAL a1 = {"Max", Dog, Male, 12, "Schoolstraat 1", {1, 2, 3}};
ANIMAL a2 = {"Kiekerjan", Cat, Female, 4, "boven in boom", {4, 3, 2}};
ANIMAL a3 = {"Lorre", Parrot, Male, 40, "werk", {8, 9, 10}};
ANIMAL a4 = {"Fifi", Dog, Female, 1, "1Kerkstraat 13", {1, 1, 100}};
ANIMAL a5 = {"Piep", GuineaPig, Male, 3, "1thuis", {3, 4, 1}};
ANIMAL a6 = {"Fifi", Dog, Female, 1, "2Kerkstraat 13", {1, 1, 100}};
ANIMAL a7 = {"Piep", GuineaPig, Male, 3, "2thuis", {3, 4, 1}};
ANIMAL a8 = {"Fifi", Dog, Female, 1, "3Kerkstraat 13", {1, 1, 100}};
ANIMAL a9 = {"Piep", GuineaPig, Male, 3, "3thuis", {3, 4, 1}};

animals[(*nrAnimals)++] = a1;
animals[(*nrAnimals)++] = a2;
animals[(*nrAnimals)++] = a3;
animals[(*nrAnimals)++] = a4;
animals[(*nrAnimals)++] = a5;
animals[(*nrAnimals)++] = a6;
animals[(*nrAnimals)++] = a7;
animals[(*nrAnimals)++] = a8;
animals[(*nrAnimals)++] = a9;
}


int writeAnimals(const char* filename, const ANIMAL* animalPtr, int nrAnimals)
 {
     if (filename == NULL || animalPtr == NULL || nrAnimals)
     {

     }
     FILE *fp;
     fp = fopen(filename, "w");
     fwrite(animalPtr, sizeof(ANIMAL),nrAnimals,fp);
     fclose(fp);
     return 0;
 }

以上是我要包含在我的文件中的结构。在我 运行 这段代码和 用 hexeditor 打开文件我只看到很多零。

File where I save the animals

我是不是做错了什么?

编辑:

void test_writeAnimals(void)
{
int nrAnimals = 0;
ANIMAL animals[10];
addTestData(animals, &nrAnimals);
int number;
FILE *fp;
number = writeAnimals("Argenis", animals, 10);
fclose(fp);
TEST_ASSERT_EQUAL(1, number);
}

我就是这样调用函数的。

typedef enum
{
Cat,
Dog,
GuineaPig,
Parrot
} SPECIES;

typedef enum
{
Male,
Female
} SEX;

typedef struct
{
int Day;
int Month;
int Year;
} DATE;

#define MaxNameLength 25
#define MaxLocationLength 100
typedef struct
{
char    Name[MaxNameLength];
SPECIES Species;
SEX     Sex;
int     Age;
char    FoundAtLocation[MaxLocationLength];
DATE    DateFound;
} ANIMAL;

函数fwrite写入您告诉它的固定数量的数据。结构中未使用的 space 不会神奇地消失。

例如struct的第一个成员是

char Name[MaxNameLength];

所以 fwrite 会将 Name 的所有 25 个字符写入文件,而不管第一个动物的名字 "Max" 只有 3 个字母。

第二个成员是 Species,您将其初始化为 Dog,因此其值为 1

第三个成员是 Sex,您将其初始化为 Male,其值为 0

此外, struct 本身被填充,以便每个成员对齐到 32 位,第一个成员 Name 实际上占用 struct 的 28 个字节,而不是 25 .

因此十六进制转储的前 28 个字节显示长度为 25 的 "Max" 加上 3 个字节的填充,然后是 01 00 00 00,这是 little 中 Dog 的 32 位值-endian格式,后跟00 00 00 00Male.

的32位值
4D 61 78 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
01 00 00 00
00 00 00 00

等等。