在函数

时间:2016-10-29 18:33:42

标签: c struct

我有一个包含多个命令的文件。当我看到正确的命令时,我必须在struct array中添加动态创建的struct。

我创建了struct但我无法将其添加到main()函数中的数组中。

以下是我的所作所为:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct book{
    char name[30];
    int page_number;
};

int main()
{
    FILE *fp;

    fp = fopen("input.txt", "r");

    if(fp == NULL){
        printf("Error opening file.");
    }

    read_line(fp);

    fclose(fp);
    return 0;
}

void read_line(FILE *fp){
    char str[100];
    while(1){
        if(fgets(str, 100, fp) != NULL){
            printf("%s", str);
            split_line(str);
        } else {
            break;
        }
    }
}

void split_line(char *line){
    char ** res  = NULL;
    char *  p    = strtok (line, " ");
    int n_spaces = 0, i;

/* split string and append tokens to 'res' */

    while (p) {
        res = realloc (res, sizeof (char*) * ++n_spaces);
        if (res == NULL){
            printf("Memory allocation failed!");
        } else {
            res[n_spaces-1] = p;
            p = strtok (NULL, " ");
        }
    }

/* realloc one extra element for the last NULL */

    res = realloc (res, sizeof (char*) * (n_spaces+1));
    res[n_spaces] = 0;

    command_check(res);
    free(res);
}

void command_check(char **tokens){
    if(strcmp(tokens[0], "CREATEBOOK") == 0){
        create_book(tokens);
    } else if (strcmp(tokens[0], "REMOVEBOOK") == 0){
        remove_book(tokens);
    }
}

void create_book(char **tokens){
    book created_book;
    strcpy(created_book.name, tokens[1]);
    created_book.page_number = atoi(tokens[2]);
    //then what im stuck here
}

0 个答案:

没有答案