【发布时间】:2015-12-20 22:27:43
【问题描述】:
我无法在 C 中解析 CSV 文件。我需要使用该文件中的数据归档一个结构。这是我的结构的相关部分:
typedef struct Info {
/* Some strings, integers, etc. */
char correct; /* This is the value I can't set */
short int status;
} t_info;
我文件中的一行看起来像这样 xxxxxx;xxxxxxx;xxxxxxx;D;254(D 是我的问题,见下文)。
char line[1024]; /* Buffer */
t_info info;
fgets(line, sizeof(line), fp);
strcpy(info.xxxxxx, getLine(line, 1)); /* Works */
strcpy(info.xxxxxx, getLine(line, 2)); /* Works */
strcpy(info.xxxxxx, getLine(line, 3)); /* Works */
strcpy(info.correct, getLine(line, 4)); /* Crashs! */
getLine() 函数取自this 帖子:
const char *getLine(char *line, int num)
{
const char *tok, *tmp = strdup(line);
for (tok = strtok(tmp, ";"); tok && *tok; tok = strtok(NULL, ";\n"))
{
if (!--num)
return tok;
}
return NULL;
}
我的问题是什么?
【问题讨论】:
-
没有深入研究过这个——如果你把D换成DD会怎样。它有效吗?也许它失败了一个字符;一些边缘情况。
-
不,不会改变任何东西。
-
你的解决方案很草率:
strdup()分配的内存无法释放,因为无法从getLine()返回的指针中计算出分配块的起始地址。此外,您不会在文件末尾测试getLine()失败,甚至fgets()失败:缺少字段的行将导致未定义的行为。事实上,具有长字段的行也会导致未定义的行为。需要更多的工作! -
感谢您的意见 :) 会调查的。