读书人

关于读取文件内容分割字符串的函数

发布时间: 2012-05-03 14:06:56 作者: rapoo

关于读取文件内容,分割字符串的函数,请教linux C。

C/C++ code
#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);}


编译运行:结果
1;jean;male;electron;communicate;no marks
Here we have 6 strings
1
jean
male
electron
communicate
no marks

info:id=144986484; name=male; sex=electron; col=communicate; sub=no marks
; marks=(null)

不懂得是:输出数组的时候正确,在存入结构体的时候,数组怎么后移了一位,导致输出错位。

本来应该是:id=1;name=jean;sex=male........

先谢谢各位大神、

[解决办法]
什么都对,就是最后错了.
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);
}
就是这里错了,id=%d对应的str->id没写进去.应该改成
int print_st(st str)
{
printf("info:id=%d; name=%s; sex=%s; col=%s; sub=%s; marks=%s\n",
str->id,str->name, str->sex, str->col, str->sub, str->marks);
}

读书人网 >C语言

热点推荐