Filter在c. 中查询文本文件



(C语言)我在一个文本文件中有以下数据,并希望过滤具有特定年龄和收入超过x工资且年龄低于y的人。

假设第一列是年龄,最后一列是工资例如

39, State-gov, 77516, Bachelors, 13, Never-married, Adm-clerical, Not-in-family, White, Male, 2174, 0, 40, United-States, <=50K
50, Self-emp-not-inc, 83311, Bachelors, 13, Married-civ-spouse, Exec-managerial, Husband, White, Male, 0, 0, 13, United-States, <=50K

看起来输入文件实际上是CSV格式的。我建议参考C

读取。csv文件
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char* getfield(char* line, int num)
{
const char* tok;
for (tok = strtok(line, ",");
tok && *tok;
tok = strtok(NULL, ";n"))
{
if (!--num)
return tok;
}
return NULL;
}
int main()
{
FILE* stream = fopen("input", "r");
char line[1024];
while (fgets(line, 1024, stream))
{
char* tmp = strdup(line);
printf("Field 3 would be %sn", getfield(tmp, 3));
// NOTE strtok clobbers tmp
free(tmp);
}
}

你也可以寻找CSV parser库,如:https://github.com/semitrivial/csv_parser

最新更新