关于读取文件内容,分割字符串的函数,请教linux C。
#include <string.h>#include <stdio.h>#include <stdlib.h>struct info{ int id; char name[10]; char sex[10]; char col[10]; char sub[15]; char marks[20];};typedef struct info *st;st head = NULL;int break_up(char *buffer);int put_in(char* str[]);int print_st(st str);int main(void){ FILE *stream; char msg[100]; /* open a file for update */ stream = fopen("file.txt","r"); /* seek to the start of the file */ fseek(stream, 0, SEEK_SET); fgets(msg, 100, stream) != NULL; fgets(msg, 100, stream) != NULL;//读取第二行的内容并处理; /* 第二行内容 1;jean;male;electron;communicate;no marks */ printf("%s",msg); break_up(msg);//分割字符串 fclose(stream); return 0;}int break_up(char *buffer){ int i = 0, j = 0; char *p[20]= {NULL}; char *buf=buffer; char *outer_ptr=NULL; char *inner_ptr=NULL; while((p[i]=strtok_r(buf,";",&outer_ptr))!=NULL) { i++; buf=NULL; } printf("Here we have %d strings\n",i); for(j=0 ; j<i; j++) { printf("%s\n",p[j]); } put_in(p); return 0;}int put_in(char* str[])//放入结构体重{ st st1 = (st)malloc(sizeof(struct info)); st1->id = atoi(str[0]); strcpy(st1->name, str[1]); strcpy(st1->sex, str[2]); strcpy(st1->col, str[3]); strcpy(st1->sub, str[4]); strcpy(st1->marks, str[5]); print_st(st1); free(st1); return 0;}int print_st(st str){ printf("info:id=%d; name=%s; sex=%s; col=%s; sub=%s; marks=%s\n", str->name, str->sex, str->col, str->sub, str->marks);}