c - 解析 CSV 文本行时出错

标签 c csv ansi-c

我无法用 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;
}

我的问题是什么?

最佳答案

无法使用 strcpy() 保存到 char 中。

typedef struct Info {
    char correct; /* This is the value I can't set */
} t_info;

strcpy(info.correct, getLine(line, 4)); /* Crashs! */

使用

info.correct = *getLine(line, 4);

您的编译器应该对此发出警告。查看编译器设置。

关于c - 解析 CSV 文本行时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34386545/

相关文章:

c - 如何从 Linux 帧缓冲区获取 RGB 像素值?

c - 如何停止在 pthread_join 上停滞的线程?

linux - 从多个 .tar.gz 文件中提取特定文件名以构建一个 .csv 文件

SQLite 导入 CSV 文件 - 预期 3 列,发现 1948

使用 fclose() 后损坏的双链表;

c - DirectX 游戏的窗口 GUI 似乎有问题

c - 本地范围内的静态

ruby - 文件对象是否应该发送给sidekiq worker

c - 将接收到的可变数量的参数传递给另一个函数

c - Mingw-w64 C版本支持吗?