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

C语言如何编辑更新CSV文件 实现修改指定用户Pin码功能

C语言CSV文件内容更新问题解决记录

需求背景

我正在开发一个需要用C语言处理.csv文件的项目,目前被CSV文件编辑更新的问题困扰,暂时未找到合适的解决方案。我使用的CSV文件结构如下:

Username, Pin, Balance

目前我已经可以正常读取CSV文件的内容,但卡在内容更新的步骤,我的需求是:根据指定用户名修改对应的Pin码值。

初始实现代码

参考大家的评论后我尝试了文件替换的实现方案,代码如下:

void change_pin(char *C){
    char line[200];
    char user[50];
    char date[50];
    char action[50];
    char user_n[50];
    char date_n[50];
    char action_n[50];
    FILE *str = fopen("Example.csv", "r+");
    FILE *new = fopen("new.csv", "w");
    if (str == NULL) {
        printf("Error opening file");
        fclose(str);
    }
    if (new == NULL) {
        printf("Error opening file");
        fclose(new);
    }

    while(fgets(line, 200, str)){
        char *token;
        token = strtok(line, ",");
        while (token != NULL){
            if (strcmp(token, C) == 0){
                strcpy(user, token);
                token = strtok(NULL, ",");
                strcpy(date, token);
                token = strtok(NULL, ",");
                strcpy(action, token);
                token = strtok(NULL, ",");
                strcpy(date, C);
                fprintf(new, "%s,%s,%s\n", user, date, action);
            }
            else{
                strcpy(user_n, token);
                token = strtok(NULL, ",");
                strcpy(date_n, token);
                token = strtok(NULL, ",");
                strcpy(action_n, token);
                token = strtok(NULL, ",");
                fprintf(new, "%s,%s,%s\n", user_n, date_n, action_n);
            }
        }
    }
    remove("Example.csv");
    rename("new.csv", "Example.csv");
    fclose(str);
    fclose(new);
}

问题与解决方案

上述代码中的strcpy(date, C)仅为测试用途,首次运行时功能正常,但第二次执行时就会报错。最终我通过删除fprintf语句中的'\n'字符解决了该问题,感谢大家提供的帮助。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 08:06:02