gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 04:45:43 24 4
gpt4 key购买 nike

下面是我目前必须从文件中读取数据的代码。当我注释掉 while 循环并尝试只读入一行数据时,我打印了一些空值或 0 值,然后是 block 中的其余数据,最后是段错误消息。当我离开 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,

最佳答案

您的 strtok 缓冲区的内容可能不是您所期望的。我肯定会采纳@Joachim 关于调试器的建议。调试器是开发期间的好 friend 。

以下是来自 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

关于c - Strtok 和 fgets Objective C 函数导致读取错误以及段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21117471/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com