Search code examples
cfile-ioiolinked-listpass-by-reference

Reading data from a file into a linked list


Hey I've got a chunk of code here which is supposed to read a file into a linked list:

void loadFile() {
    Event *event;
    FILE *file;
    int nRead = 7;
    char filename[30];
    LinkedList *list;

    list = (LinkedList*)malloc(sizeof(LinkedList));
    event = (Event*)malloc(sizeof(Event));

    printf("Please input filename\n");
    scanf("%s", filename);
    file = fopen(filename, "r");

    nRead = fscanf(file, "%d-%d-%d %d:%d %d %s", &(list->head->event->date->year), &(list->head->event->date->month), &(list->head->event->date->day), &(list->head->event->time->hours), &(list->head->event->time->minutes), &(list->head->event->duration), event->name);

    if(nRead != 7) {
        printf("Error in reading file.\n");
    }

    fclose(file);
}

and here I've got some part of my main

int main(int argc, char **argv) { 
  Window *window;
  Event *event;
    FILE *file;

    window = createWindow("Calendar");

    if(argc == 2) {
        file = fopen(argv[1], "r");
            if(file == NULL) {
                printf("Could not open file.\n");
            } else {
                    printf("File opened successfully!\n");
                }
    }
    else {
    addButton(window, "Load a calendar from file.", *loadFile(), &event); //ERROR HERE
    }
}

here is the addButton(no need to know functionality, just need syntax help)

void addButton(Window *window, char *label, void (*callback)(void*), void *data);

I get the error:

assignment.c: In function ‘main’:
assignment.c:22: error: void value not ignored as it ought to be

I really don't know why and I'm stuck in this part. I've looked around and I see that the void value not ignored error happens when you assign a function with a void return to a variable or something but I don't think I'm doing that in my code...

any help would be kindly appreciated


Solution

  • Change your code to:

    addButton(window, "Load a calendar from file.", loadFile, &event);
    

    You were passing *loadFile(), which actually calls the loadFile function and then tries to dereference the void return value. What you intended to do was pass a pointer to the function.

    There is a slight problem still, because addButton is expecting void (*callback)(void*). ie, you are supposed to pass a void function that has a single void* parameter. But loadFile does not match. To fix this, you should declare loadFile to accept a void* parameter.

    void loadFile( void *data ) {
        /* etc... */
    }