Strtok和fgets Objective C函数导致读取错误以及分段错误

时间:2014-01-14 15:36:40

标签: c segmentation-fault fgets strtok

以下是我目前必须从文件中读取数据的代码。当我注释掉while循环并尝试只读取一行数据时,我会得到一些空值或0值,然后是块中的其余数据,最后是分段错误消息。当我离开while循环时,我只得到分段错误消息。但是,如果我选择只读取第一个变量而没有循环,一切正常。下面我已经包含了我的代码和测试文件。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BUF_LEN 1024

int main(){

FILE *file;
int i;
char *SywUserId, *IntractnId, *DivNbr, *ItemNbr, *KsnId, *buddy_cnt, *cnt_rank,      *table_type, *summer_active, *winter_active;
char buf[BUF_LEN];

file = fopen( "ea_test_rec.txt" , "r");

fgets(buf, BUF_LEN, file); 
while(!feof(file)) {
    if(strlen(buf) < 2) break;
    i=strlen(buf)-1; while(i > 0 && buf[i] <= ' ') buf[i--] = '\0';
    SywUserId = strtok(buf, ",");
    table_type = strtok(NULL, ",");
    cnt_rank = strtok(NULL, ",");
    IntractnId = strtok(NULL, ",");
    DivNbr = strtok(NULL, ",");
    ItemNbr = strtok(NULL, ",");
    KsnId = strtok(NULL, ",");
    buddy_cnt = strtok(NULL, ",");
    summer_active = strtok(NULL, ",");
    winter_active = strtok(NULL, ",");

    printf("%s:%s:%s:%s:%s:%s:%s:%s:%s:%s\n", (SywUserId, table_type, cnt_rank, IntractnId, DivNbr, ItemNbr, KsnId, buddy_cnt, summer_active, winter_active));
            fgets(buf, BUF_LEN, file);
}
    fclose(file);
}

ea_test_rec.txt

1,1,1,-276551,7,63062,0,1.993,0,0,
1,1,10,24315147,54,41796,0,1.934,0,0,
1,1,11,25562371,2,40396,3747849,1.934,0,0,
1,1,12,-948793,2,2820,0,1.919,0,0,
1,1,13,4272725,44,20243,0,1.911,0,0,
1,1,14,2917566,44,71641,0,1.900,0,0,
1,1,15,24655338,54,71593,0,1.898,0,0,
1,1,16,22365342,44,67862,0,1.894,0,0,
1,1,17,12690269,44,14216,0,1.886,0,0,
1,1,18,2920093,44,93074,0,1.875,0,0,
1,1,19,8569801,2,40396,0,1.868,0,0,
1,1,2,-273684,7,63204,0,1.984,0,0,
1,1,20,10171246,88,2379,0,1.859,0,0,
1,1,3,1617035,44,72854,0,1.977,0,0,
1,1,4,12690127,44,14602,0,1.973,0,0,
1,1,5,13064870,44,13666,0,1.966,0,0,
1,1,6,1616493,44,34869,0,1.966,0,0,
1,1,7,1617032,44,72854,0,1.956,0,0,
1,1,8,1616460,44,23337,0,1.950,0,0,
1,1,9,24655107,2,94350,0,1.948,0,0,

1 个答案:

答案 0 :(得分:0)

strtok缓冲区的内容可能与您的预期不符。我肯定会接受@Joachim关于调试器的建议。在开发时间,调试器是一个很好的朋友。

以下是来自strtok()'第一行缓冲区的字符串结果的图像:

enter image description here

从printf语句中删除不必要的() ...即从以下位置更改printf语句:

printf("%s:%s:%s:%s:%s:%s:%s:%s:%s:%s\n", (SywUserId, table_type, cnt_rank, IntractnId, DivNbr, ItemNbr, KsnId, buddy_cnt, summer_active, winter_active));

要:

printf("%s:%s:%s:%s:%s:%s:%s:%s:%s:%s\n", SywUserId, table_type, cnt_rank, IntractnId, DivNbr, ItemNbr, KsnId, buddy_cnt, summer_active, winter_active);

进行这些更改后的输出:

enter image description here