首页 > 解决方案 > 如何使用c删除csv文件的特定列

问题描述

这是我的 csv 文件,我想获取名称以“A”开头的特定行,只有 1,2 和 6 列。例如,像 bread,anname,Ot 这样的列不应该出现在输出中。我附上了我需要的输入和输出。请帮助。

输入如下图:

Name,id,bread,anName,Ot,number
A,1,animal,tiger,op,2.1vd
M,2,animal,toper,ip,9.1vd
A1,7,animal,dog,cp,Na11
A2,9,animal,mouse,ap,0
A23,9,animal,pouch,gp,Na11

输出应该是:

A,1,2.1vd
A1,7,Na11
A2,9,0
A23,9,Na11

代码

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

#define NUMLETTERS 5000

typedef struct {
    char Name[100];
    int id;
    char bread[200];
    char anName[200];
    char ot[200];
    char Number[200];

} record_t;

int main (int argc, char **argv) {

    record_t records[NUMLETTERS];
    char buf[6 * NUMLETTERS] = "";
    int count = 0, i;

    /* use filename provided as 1st argument (stdin by default) */
    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;
      fp = fopen("letters.csv", "r");

    if (!fp) {  /* validate file open for reading */
        perror ("file open failed");
        return 1;
    }

    while (fgets (buf, sizeof buf, fp)) {   /* read each line into buf */
        record_t tmp = { .Name = "" };    
        if (*buf != 'A')                    
            continue;
        if (sscanf (buf, " %99[^,],%d,%[^\n],%s,%s,%s",
                    tmp.Name, &tmp.id, tmp.bread, tmp.anName, tmp.Ot, tmp.Number) == 6)
            records[count++] = tmp;
        else
            fprintf (stderr, "%d A record - invalid format.\n", count + 1);
    }

    if (fp != stdin)   /* close file if not stdin */
        fclose (fp);

    for (i = 0; i < count; i++)
#ifdef WITHPIN
        printf ("%-8s %2d     %s,%s,%s,%s\n",
                records[i].Name, records[i].id, records[i].bread, records[i].anName, records[i].Ot, records[i].Number);
#else
        printf ("%-8s     %d,%s\n", records[i].Name, records[i].id, records[i].Number);
#endif
}

标签: carrayscsvstruct

解决方案


推荐阅读