简体   繁体   中英

Using fgets and strtok to read a file in C?

I am currently writing a small program for school and we have to use fgets and strtok to read the file.

input.txt is:
Redden 2 0
Berglund 5 2
Jackman 2 0
Stewart 4 0
Oshie 3 5
McDonald 2 4

Here is the relevant code

int main(int arg, char *argv[]) {
    FILE *fp=fopen(argv[1]);
    char **names=NULL;
    int *goals=NULL;
    int *assists=NULL;
    int size = countLinesInFile(fp);
    allocateMemory(&goals, &assists, &names, size);
    readLines(fp, goals, assists, names, size);
}

void allocateMemory(int** goals, int** assists, char*** names, int size) {
    *goals = malloc(size*sizeof(int));
    *assists = malloc(size*sizeof(int));
    *names = malloc(size*sizeof(char *));
    int i;
    for(i=0; i<size; i++)
    {
       *(*names + i) = malloc(MAX_NAME*sizeof(char));
    }
}

void readLines(FILE *ptr, int *goals, int *assists, char **names, int size) {
    char *line=malloc(MAX_LINE*sizeof(char));
    int i;
    char *token=NULL;
    for(i=0;i<size;i++) {
        if(fgets(line,MAX_LINE, ptr)!=NULL); {
            token=strtok(line,"");//segfaulting somewhere around these lines
            strcpy(names[i],token);
            token=strtok(NULL,"\n");
            goals[i]=atoi(token);
            token=strtok(NULL,"\n");
            assists[i]=atoi(token);
        }
    }
    free(line);
}

So I am segfaulting and it's telling me it's occurring in the readLines function and have no idea how to fix this. Any help is appreciated. Thanks!

One problem is the calls to strtok . Your file uses space as delimiter, so you should do the same:

    if(fgets(line,MAX_LINE, ptr)!=NULL); {
        token=strtok(line," ");
        strcpy(names[i],token);
        token=strtok(NULL," ");
        goals[i]=atoi(token);
        token=strtok(NULL," ");
        assists[i]=atoi(token);
    }

Note that the third token will contain a \\n character. The \\n is ignored by atoi . If you want it stripped from the returned token, substitute " \\n" for the last argument to strtok .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM