lundi 2 mars 2015

Rewind a text file and populate dynamic array. Stream passed by value



this function will rewind file, create the dynamic array (of size), and read in the data, populating the _data struct dynamic array. Note that stream is passed by value this time. The function then returns the populated array of struct



struct _data
{
char* name;
long number;
};

struct _data *load(FILE *stream, int size)
{
struct _data BlackBox = calloc(size, sizeof(_data));

char tempName[3];

stream = fopen("names.txt", "r");
for (int i=0; i<size; i++)
{
fscanf(stream, "%s %ld", tempName, &data.number);
BlackBox[i].name = calloc(strlen(tempName), sizeof(char));
strcpy(BlackBox[i].name, tempName);
}
fclose(stream);

return &BlackBox;
}

File Content
ron 7774013
jon 7774014


I am a beginner and having difficulty designing the code. Can someone please explain. Thanks




Aucun commentaire:

Enregistrer un commentaire