2017-05-21 20 views
0
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打開文件,我只看到很多零。C fwrite()不會保存文件中的每個數據

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; 
+0

什麼是「狗」,「貓」,...他們不是字符串,對吧?他們是在一個枚舉或什麼? – lpares12

+0

@ lpares12我只包括枚舉。 –

回答

3

功能fwrite寫入您告訴它的固定數量的數據。結構中未使用的空間不會神奇消失。

例如,struct的第一個成員是

char Name[MaxNameLength]; 

所以fwrite會的Name所有25個字符寫入文件,而不管事實的第一個動物的名字「最大」只有3個字母。

第二位成員是Species,您初始化爲Dog,所以值爲1

第三位成員是Sex,您初始化爲Male並且其值爲0

此外,struct本身被填充,使得每個部件被對準到32位,並且所述第一構件Name實際發生28個字節的struct的,不25.

因此,第一個28個字節十六進制的轉儲顯示「最大」長度爲25加3個字節的填充,然後是01 00 00 00,這是小尾​​數格式的Dog的32位值,接着是00 00 00 00,332位值Male

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 

等等。

+0

所以所有的數據都在文件中,什麼時候想用fread讀取它應該返回所有的值? –

+0

它應該這樣做,只要讀回到相同的'struct'。但是,如果結構體包含指針,那麼它會很危險,因爲這些內存指針在讀回時是沒有意義的。在這種情況下應該找到另一種方式。 –

相關問題