Im working on function which reads text file. Function should find out how many records the text file have and malloc
an array of structures. It must be array of structures because it is specified in my assignment. LineCounter
holds value of how big the array should be. It has value 17 which is correct but when I malloc
the array it only have size of 4
structs. I am programming in C and I am also including <stdlib.h>
but the compiler is still forcing me to cast malloc.
// SEPARATE HEADER FILE
#pragma once
#define FILECITATEL "citatel.txt" // textovy subor obsahujuci zoznam citatelov
typedef struct Citatel {
int id; // id cislo citatela
char meno[20]; // meno citatela
char priezvisko[30]; // priezvisko citatela
};
Citatel *getReaders();
void printReaders(Citatel *listOfReaders);
// END OF HEADER FILE
Citatel *getReaders() {
FILE *fileRead;
fileRead = fopen(FILECITATEL, "r");
if (fileRead == NULL) {
printf("File cannot be opened!...");
return NULL;
}
char readCharacter;
int lineCounter = 0;
while ((readCharacter = fgetc(fileRead)) != EOF) {
if (readCharacter == '\n') lineCounter++;
}
if (readCharacter == EOF) lineCounter++;
rewind(fileRead);
Citatel *list = (Citatel *)malloc(lineCounter * sizeof(Citatel));
for (int i = 0; i < lineCounter; i++) {
fscanf(fileRead, "%d %s %s", &list[i].id, &list[i].meno, &list[i].priezvisko);
}
printf("%d\n", sizeof list);
fclose(fileRead);
return list;
}