从CSV文件读取并分离字段以存储在C中的结构中

如何解决从CSV文件读取并分离字段以存储在C中的结构中

我正在尝试从CSV文件读取并将每个字段存储到结构内的变量中。我正在使用fgets和strtok来分隔每个字段。但是,我无法处理包含逗号在内的特殊字段。

typedef struct {
    char name[20+1];
    char surname[20+1];
    char uniqueId[10+1];
    char address[150+1];
} employee_t;

void readFile(FILE *fp,employee_t *employees[]){
    int i=0;
    char buffer[205];
    char *tmp;
    
    while (fgets(buffer,205,fp) != NULL) {
        employee_t *new = (employee_t *)malloc(sizeof(*new));
        
        tmp = strtok(buffer,",");
        strcpy(new->name,tmp);
        
        tmp = strtok(buffer,");
        strcpy(new->surname,");
        strcpy(new->uniqueId,tmp);

        tmp = strtok(buffer,");
        strcpy(new->address,tmp);

        employees[i++] = new;
        free(new);
    }
}

输入如下:

Jim,Hunter,9239234245,"8/1 Hill Street,New Hampshire"
Jay,Rooney,92364434245,"122 McKay Street,Old Town"
Ray,Bundy,923912345,NOT SPECIFIED

我尝试使用此代码打印令牌,并且得到以下信息:

Jim 
Hunter 
9239234245
"8/1 Hill Street
 New Hampshire"

我不确定如何处理地址字段,因为其中一些可能在其中包含逗号。我尝试逐个字符地读取字符,但不确定如何使用单个循环将字符串插入结构中。有人可以帮我一些解决方法吗?

解决方法

strcspn可用于查找双引号或双引号加逗号。
原始字符串未经修改,因此可以使用字符串文字。
双引号的位置不重要。它们可以在任何字段中。

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

int main( void) {

    char *string[] = {
        "Jim,Hunter,9239234245,\"8/1 Hill Street,New Hampshire\"","Jay,Rooney,92364434245,\"122 McKay Street,Old Town\"","Ray,Bundy,923912345,NOT SPECIFIED",\" double quote here\",NOT SPECIFIED"
    };

    for ( int each = 0; each < 4; ++each) {
        char *token = string[each];
        char *p = string[each];

        while ( *p) {
            if ( '\"' == *p) {//at a double quote
                p += strcspn ( p + 1,"\"");//advance to next double quote
                p += 2;//to include the opening and closing double quotes
            }
            else {
                p += strcspn ( p,",\"");//advance to a comma or double quote
            }
            int span = ( int)( p - token);
            if ( span) {
                printf ( "token:%.*s\n",span,token);//print span characters

                //copy to another array
            }
            if ( *p) {//not at terminating zero
                ++p;//do not skip consecutive delimiters

                token = p;//start of next token
            }
        }
    }
    return 0;
}

编辑:复制到变量
计数器可用于跟踪字段的处理过程。

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

#define SIZENAME 21
#define SIZEID 11
#define SIZEADDR 151

typedef struct {
    char name[SIZENAME];
    char surname[SIZENAME];
    char uniqueId[SIZEID];
    char address[SIZEADDR];
} employee_t;

int main( void) {

    char *string[] = {
        "Jim,\"quote\",NOT SPECIFIED"
    };
    employee_t *employees = malloc ( sizeof *employees * 4);
    if ( ! employees) {
        fprintf ( stderr,"problem malloc\n");
        return 1;
    }

    for ( int each = 0; each < 4; ++each) {
        char *token = string[each];
        char *p = string[each];
        int field = 0;

        while ( *p) {
            if ( '\"' == *p) {
                p += strcspn ( p + 1,"\"");//advance to a delimiter
                p += 2;//to include the opening and closing double quotes
            }
            else {
                p += strcspn ( p,\"");//advance to a delimiter
            }
            int span = ( int)( p - token);
            if ( span) {
                ++field;
                if ( 1 == field) {
                    if ( span < SIZENAME) {
                        strncpy ( employees[each].name,token,span);
                        employees[each].name[span] = 0;
                        printf ( "copied:%s\n",employees[each].name);//print span characters
                    }
                }
                if ( 2 == field) {
                    if ( span < SIZENAME) {
                        strncpy ( employees[each].surname,span);
                        employees[each].surname[span] = 0;
                        printf ( "copied:%s\n",employees[each].surname);//print span characters
                    }
                }
                if ( 3 == field) {
                    if ( span < SIZEID) {
                        strncpy ( employees[each].uniqueId,span);
                        employees[each].uniqueId[span] = 0;
                        printf ( "copied:%s\n",employees[each].uniqueId);//print span characters
                    }
                }
                if ( 4 == field) {
                    if ( span < SIZEADDR) {
                        strncpy ( employees[each].address,span);
                        employees[each].address[span] = 0;
                        printf ( "copied:%s\n",employees[each].address);//print span characters
                    }
                }
            }
            if ( *p) {//not at terminating zero
                ++p;//do not skip consceutive delimiters

                token = p;//start of next token
            }
        }
    }
    free ( employees);
    return 0;
}
,

在我看来,这种问题需要“适当的”令牌生成器,它可能基于有限状态机(FSM)。在这种情况下,您将逐字符扫描输入的字符串,并将每个字符分配给一个类。令牌生成器将以特定状态开始,并且根据所读取字符的类别,它可能保持相同状态,或移至新状态。也就是说,状态转换由当前状态和所考虑字符的组合来控制。

例如,如果在开始状态下阅读双引号,则将转换为“在带引号的字符串中”状态。在这种状态下,逗号不会导致转换为新状态-只会将其添加到您正在构建的令牌中。在任何其他状态下,逗号都具有特殊的意义,表示令牌的结尾。您必须弄清楚何时需要在标记之间添加额外的空格,是否存在一些“转义符”允许在其他标记中使用双引号,是否可以转义换行符更长的线,依此类推。

重要的一点是,如果您实现的是FSM(或其他真正的令牌生成器),则实际上您可以 考虑所有这些内容,并根据需要实现它们。如果您使用临时应用程序strtok()和字符串搜索,则无论如何都不能以一种优雅,可维护的方式。

如果有一天,您最终需要使用宽字符来完成整个工作,那很容易-只需将输入转换为宽字符并一次将其迭代一个宽字符(而不是字节)即可。

使用状态转换图来记录FSM解析器的行为很容易-至少更容易通过以文本形式记录代码来解释它。

我的经验是,有人第一次实现FSM令牌生成器,这太可怕了。之后,这很容易。而且,当您知道该方法时,可以使用相同的技术来分析复杂性更高的输入。

,

这是从记录中提取字段的另一种方法。

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

int main( void) {
    char record[] = " Henry \"Doc\",Thomas,\"21 \"\"Hampston\"\" Road\"";
    char *text = NULL;
    char *tmp = NULL;
    char *element = record;
    int last = 0;
    int current = 0;
    int field = 0;
    int word = 0;
    int quote = 0;
    int output = 0;

    if ( ( tmp = realloc ( text,strlen ( element) + 1)) == NULL) {
        fprintf ( stderr,"could not allocate memory\n");
        return 1;
    }
    text = tmp;
    *text = 0;

    while ( *element) {//stop at zero that ends string
        current = *element;//current character
        switch ( *element) {
            case ','://ends field
                if ( quote) {//except inside quotes
                    break;
                }
                current = 0;//don't use current character
                output = 1;//output the field
                break;
            case '\t':
            case ' ':
                if ( ! word) {//don't use whitespace at start of field
                    current = 0;//don't use current character
                }
                break;
            case '\"':
                quote = ! quote;
                if ( '\"' == last) {
                    current = 0;//don't use current character
                    break;
                }
            default:
                word = 1;
                break;
        }
        if ( current) {
            *tmp++ = *element;
            *tmp = 0;
        }

        last = *element;
        ++element;

        if ( output || ( ! *element && *text)) {
            ++field;
            printf ( "field %d %s\n",field,text);
            tmp = text;
            *tmp = 0;
            word = 0;
            output = 0;
        }
    }
    free ( text);
    return 0;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-