从文本文件中读取一行,并在struct中放置由空格分隔的数据

我要在C中编写一个函数,它将filepointer作为输入并返回如下结构:

typedef struct product{ char * code_product; char * name; char * code_piece; only_time_t enter; only_time_t exit; }product_t; 

这个结构使用另一个这样的结构:

 typedef struct only_time{ int hour; int minute; int second; }only_time_t; 

为了从文件中读取,我使用了getline()函数,我使用strtok()函数来创建令牌。 这是我用来从文件中读取的函数:

 product_t * read_line(FILE * fp){ char * line = NULL; size_t len = 0; product_t * temp; int i = 0; temp = (product_t *) malloc(sizeof(product_t)); temp->code_product = (char *) malloc(sizeof(char) * 4); temp->name = (char *) malloc(sizeof(char) * 60); temp->code_piece = (char *) malloc(sizeof(char) * 4); //read a line from the file getline(&line, &len, fp); //handle line info info char *tokens[80]; tokens[0] = strtok(line," ,."); while (tokens[i] != NULL) { i++; tokens[i] = strtok(NULL," ,."); } temp->code_product = tokens[0]; temp->name = tokens[1]; temp->code_piece = tokens[2]; temp->enter = timestring_to_time(tokens[3]); temp->exit = timestring_to_time(tokens[4]); //cleanup if (line) free(line); return(temp); } 

为了看看程序读了什么,我使用一个打印结构的简单函数:

 void print_product(product_t * product){ printf("product_t code_product: %s \n", product->code_product); printf("product_t name: %s \n", product->name); printf("product_t code_piece: %s \n", product->code_piece); printf("product_t enter: %d:%d:%d \n", product->enter.hour,product->enter.minute,product->enter.second); printf("product_t exit: %d:%d:%d \n", product->exit.hour,product->exit.minute,product->exit.second); } 

我已经设置了一个测试用例,它在文本文件中有以下行(称为test.txt,并放在与可执行文件相同的文件夹中):

H235 Sportello_dx N246 15:20:43 15:27:55

但是该程序的输出是:

 product_t code_product:   )   product_t name: product_t code_piece: N246 product_t enter: 15:20:43 product_t exit: 15:27:55 

这是一个可以运行整个代码的pastebin: https : //pastebin.com/9rz0vM5G

为什么我得到前2行的这个奇怪的输出,但其余的工作?

strtok()在解析字符串时修改字符串,并在您的case line返回指向同一字符串内部的指针。 因此,当您稍后free(line) ,释放temp结构引用的内存。 研究strdup()