c - 如何使用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
}
解决方案
推荐阅读
- microcontroller - 控制 4 位 7 段 LED 接口 MCU 8051
- multithreading - OpenGL PBO 映射缓冲区:多线程解包慢,memcpy 快
- php - PHP - 命令行中的服务器名称
- php - Laravel $刀片之谜中的错误
- javascript - 如果在表单验证中的 if 条件之后,我怎样才能使它变得更好
- r - 在闪亮的不工作中部署 R 程序
- php - 碳逐月获得数字回报三月 2
- java - Pivotal GemFire 多会话的 Spring 会话
- powershell - 网格中的多行
- laravel - Laravel 5.6 队列重启 CPU 使用率