我正在使用 vc2010,我试图将文件的内容读取到结构中,如下所示,它给了我运行时错误。
char buf[100];
char *token = NULL;
while( fgets (buf , 100 , rd) != NULL )
{
token = strtok( buf,", ");
test_st.fp.chunk_offset = atol(token);
printf("\n %llu ", test_st.fp.chunk_offset);
//OPTION 1: if i do this there will be no runtime error but the same
// value as the first token will be assigned to chunk_length
token = strtok(buf, ",");
//OPTION 2: this line gives error in the second while loop iteration
token=strtok(NULL,",");
test_st.fp.chunk_length = atol(token);
printf("%llu ", test_st.fp.chunk_length);
token = strtok(NULL, " ");
....
}
我的另一个问题是如何使用 strtok() 或任何(如果有的话)将一个非常长的字符串(如以下文件内容中第二个逗号后面的字符串)分配给结构数据成员(在这种情况进入fp.fing_print)?
这是我要读取的文件的第一部分
0,4096,2ed692b40e335f7c20b71c5ed0486634
4096,3028,da40bf20c8ff189087b8bd7e8580118a
7124,2177,e6dfaee81e96095d302c82f9fd73dc55
9301,1128,76201eadff3c89a381a314ed311f75ff
我试图将其读入的结构定义是:
typedef struct fpinfo
{
unsigned long chunk_offset;
unsigned long chunk_length;
unsigned char fing_print[32];
}fpinfo;
typedef struct Hash_Entry {
struct Hash_Entry *next; /* Link entries within same bucket. */
unsigned namehash; /* hash value of key */
struct fpinfo fp;
} Hash_Entry;
编辑:
是的,你是对的,我必须使用第二个选项。
我发现这个有问题。该文件每行之间都有空行,当到达这些空行时会给出错误消息。
但是我陷入了另一个问题,我必须将每行的最后一部分读入结构的数组成员(fp.fing_print)。
谢谢大家的帮助!!!
编辑: fing_print[32] 数组应该保存 32 个字符,这些字符是 md5 哈希函数的结果。我不确定是否必须将其设为空终止字符串。如果你们能给我一些建议,我将不胜感激。
最佳答案
正如paulsm4所述,您需要检查strtok()
返回值。以下代码有效并包含字符串的创建:
while( fgets (buf , 100 , rd) != NULL )
{
token = strtok(buf,", \n");
if (0 != token)
{
test_st.fp.chunk_offset = atol(token);
printf("\tchunk_offset=%lu\n", test_st.fp.chunk_offset);
token = strtok(0, ", \n");
}
if (0 != token)
{
test_st.fp.chunk_length = atol(token);
printf("\tchunk_length=%lu\n", test_st.fp.chunk_length);
token = strtok(0, ", \n");
}
if (0 != token)
{
/* EDIT: fing_print datatype changed. */
memset(test_st.fp.fing_print, 0, sizeof(test_st.fp.fing_print));
strncpy(test_st.fp.fing_print,
token,
sizeof(test_st.fp.fing_print) - 1);
/* test_st.fp.fing_print = _strdup(token); */
printf("\tfing_print=[%s]\n", test_st.fp.fing_print);
}
printf("\n");
}
分隔符设置为 ",\n"
,因为 fgets()
会将换行符读入 buf
。
关于c - 以下 strtok() 用法有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8978063/