繁体   English   中英

读取 C 中的 csv 文件,字符串内有逗号

[英]read csv file in C with commas inside strings

我有一个用逗号作为分隔符的 csv 文件,但是里面有带逗号的字符串值,所以 mi 代码也把它分开了


    char buffer[1024];

    int row = 0;
    int column = 0;

    while (fgets(buffer,1024, fp)) {
        column = 0;
        row++;
        
        if (row == 1)
            continue;
        
        char* value = strtok(buffer, ",");

        while (value) {
            if (column == 0) {
                printf("Titulo :");
            }
            if (column == 1) {
                printf("\tAutor :");
            }
            if (column == 2) {
                printf("\tanio :");
            }
            if (column == 3) {
                printf("\testante_numero :");
            }
            if (column == 4) {
                printf("\testante_seccion :");
            }
            if (column == 5) {
                printf("\tpiso :");
            }
            if (column == 6) {
                printf("\tedificio :");
            }
            if (column == 7) {
                printf("\tsede :");
            }

            printf("%s", value);
            value = strtok(NULL, ",");
            column++;
        }

        printf("\n");
    }

    // Close the file
    fclose(fp);

csv 文件的一行示例: “Structure and Interpretation of Computer Programs”,“Abelson, Sussman, and Sussman”,1996,4,“Lenguajes de Programacion”,2,“B”,“Vina del Mar”

我的 output: Titulo :“计算机程序的结构和解释”作者:“Abelson anio:Sussman estante_numero:和 Sus sman”estante_seccion:1996 piso:4 edificio:“Lenguajes de Programacion”sede:2“B”“Vina del Mar”

我该如何修复我的代码?

CSV 文件中的字段以逗号分隔,记录以换行符终止。 因此,我们的想法是逐行读取文件,识别定界逗号,但忽略嵌入的逗号。

下面的示例并不是一个完美的解决方案,它将实现 CSV 规范的所有规则,而只是一个如何使用提供的信息解析文件的示例。

如果文件包含 header 行,则可以读取每个字段名称并将其存储在一个字符串数组中,以获得更通用的方法。 此外,如果需要对数据进行一些进一步的操作(可能是排序),则可以使用结构。

包括一些注释来解释代码。

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

#define BUFF_SIZE 1024
#define NR_FIELDS 8

int main(void)
{
    char buffer[BUFF_SIZE];

    char *field[NR_FIELDS] = {"Titulo", "Autor", "Anio", "Estante numero", "Estante seccion", "Piso", "Edificio", "Sede"};
    char *pos, *lastPos;

    FILE *fp = fopen("file.csv", "r");
    if (fp == NULL)
    {
        printf("Error opening the file.");
        exit(1);
    }

// read each line to a buffer
    while (fgets(buffer, BUFF_SIZE, fp) != NULL) 
    {
         int i = 0;
         _Bool inString = 0;

        pos = lastPos = buffer;

/* read characters from the buffer. If " is read, consider it beginning of the 
string and ignore subsequent commas, until second " is read */
        do 
        {
            if (*pos == '\"')
                inString = !inString;

/* if ',' is read or the end of the line is reached, while not inside a string, 
consider it a field delimiter and print the field, preceded by field name */
            if ((*pos == ',' || (*pos == '\0' && i == NR_FIELDS - 1)) && !inString)
            {
                printf("%s: %.*s", field[i++], pos - lastPos, lastPos);
                if (*pos)
// add space between the fields if not at the end of the line
                    printf(" ");
                lastPos = pos + 1;
            }
        } while (*pos++ && i < NR_FIELDS);

    } 
    fclose(fp);

    return 0;
}  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM