简体   繁体   中英

Reading in character strings from text file in C

I need to write a program that reads in strings from a text file and stores each word in a struct, ie if the first line in the text file is:

TOYOTA COROLLA 2014 WHITE

Toyota would go into structname.model, corolla would go into structname.make, etc. I am having trouble with reading each string into their according element in the struct. My source code (which I have not posted here bc it is very long and a large percentage of it is pretty irrelevant to this problem) compiles with no errors, but I am 99% sure it is a problem with my loop which is supposed to be reading in the values:

carRecord cars[10]; //declares array of structs containing carRecord info
char filename[256];
char buf[256];
FILE *carfile;

printf("Please enter the name of a file to read car records from (followed by the file extension): ");
scanf("%s", filename);

carfile = fopen(filename, "r");

if (!carfile)
{
    printf("File failed to open.\n");
}

printf("ERROR CHECK 1");

int i = 0;
while ((fgets(buf, sizeof(buf), carfile) != NULL) && i < 10)
{
    cars[i].make = strdup(strtok(buf, " "));

    cars[i].model = strdup(strtok(buf, " "));

    cars[i].year = atoi(strdup(strtok(buf, " ")));

    cars[i].color = strdup(strtok(buf, " "));

    i++;
}

The first error check prints, and then the program crashes. I have a strong, scary feeling this has to do with the malloc command, but I am pretty new to C and have absolutely no idea how to implement it.

If at all helpful, the struct declaration for carRecord is:

struct carRecord{
    char* make;     //make of car
    char* model;    //model of car
    int year;           //year of car
    char* color;    //color of car
};

(EDIT: code has been updated to reflect below comments)

I am pretty sure, if you allocate memory to the structure elements, you'll get desired result. Else, as you mentioned, use calloc/malloc.

struct carRecord{
    char make[100];     //make of car
    char model[100];    //model of car
    int year;           //year of car
    char color[100];    //color of car
};

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