You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C语言更新CSV文件指定行的目标列单元格内容

问题描述

现有一段C语言CSV读写代码,已实现查找town列中值为LA的行,需要添加功能:将该行相邻的rss列内容替换为POP。

CSV初始内容

townrsssoc
LAsolsap
BAkolkap

当前代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// 解析CSV行,获取指定列的内容(分隔符为逗号)
const char *getfield(char *line, int num)
{
    const char *tok;
    for (tok = strtok(line, ",");
         tok && *tok;
         tok = strtok(NULL, ",\n"))
    {
        if (!--num)
            return tok;
    }
    return NULL;
}

int main()
{
    char *name;
    FILE *fp;
    fp = fopen("file.csv", "r+");
    int result;
    char line[1024];
    while (fgets(line, 1024, fp))
    {
        char *tmp = strdup(line);
        getfield(tmp, 1);
        // 比较目标字符串与当前行第一列内容
        name = "LA";
        result = strcmp(name, tmp);
        // 匹配到目标行
        if (result == 0)
        {
            char *tmp2 = strdup(line);
            printf("原第二列内容为:%s\n", getfield(tmp2, 2));
            // 此处需将第二列内容替换为POP
            fprintf(fp, "POP");
        }
        free(tmp);
    }
}

预期更新后的CSV内容

townrsssoc
LAPOPsap
BAkolkap

内容的提问来源于stack exchange,提问作者GPA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 05:50:39