I'm attempting to read from a text file that will have its first value being the amount of entries within the text. With this value, i will create a for loop that will assign the date and texts into a specific struct, until all entries have been placed in a struct. It will also print the values through each for loop. However, when compiling, it gives segmentation fault: 11. Could you please explain, i'm not very good at structs and malloc. Thank you in advance.
(Please note, the text dates printed are intentionally different to those in the text file for my assignment).
#include <stdio.h>
#include<string.h>
#include<stdlib.h>
#include"journal.h"
int main(int argc, char* argv[])
{
FILE* journal;
int i, numentries;
Entry* entries;
Entry* temp;
if (argc != 2)
{
printf("Index required");
}
fscanf(journal, "%d", &numentries);
entries = (Entry*)malloc((numentries)*sizeof(Entry));
for(i=0; i<numentries; i++)
{
fscanf(journal,"%2d/%2d/%4d", &entries[i].day, &entries[i].month, &entries[i].year);
fgets(entries[i].text, 101, journal);
printf("%4d-%2d-%2d: %s", entries[i].year, entries[i].month, entries[i].day, entries[i].text);
}
fclose(journal);
return 0;
}
with my header file (journal) being ->
typedef struct {
int day;
int month;
int year;
char text[101];
}Entry;
Entry entries;
An example of the text file will be:
2
12/04/2010
Interview went well i think, though was told to wear shoes.
18/04/2010
Doc advised me to concentrate on something... I forgot.