gpt4 book ai didi

解析文件的C程序

转载 作者:行者123 更新时间:2023-12-04 10:43:10 24 4
gpt4 key购买 nike

我有一个 CSV 文件,格式为:

name,num-one,num-two,num-three

我有一个我使用的解析脚本(如下),但我想编辑该脚本以在继续之前检查整个文件。

脚本伪代码:

Read through the whole file/
Find a line where token 1 matches a set value AND
Token two matches another set value THEN
Set the value two tokens as new variables
Otherwise move onto the next line.

如果 token 一 (name) 和 token 二 (num-one) 等于我的程序当前正在处理的值,则将 token 三和四设置为value1value2

char    line[32];
int count;
FILE *read_file;

read_file = fopen ("/location/of/file.csv", "r");

fgets (line,32,read_file);

pch = strtok (line,",");

while (pch != NULL )
{
if (count == 1)
{
if ( (strcmp(pch,name) == 0) )
{
count++;
}
}
else if (count == 2)
{
if ( (strcmp(pch,num-one) == 0) )
{
count++;
}
}
else if (count == 3)
{
value1 = atoi(pch);
count++;
}
else if (count == 4)
{
value2 = atoi(pch);
count = 1;
}
pch = strtok (NULL, ",");
}

最佳答案

你真的不应该为这样的事情使用 strtok()

相反,做更简单的事情:

  1. 使用fgets() 读取一行。你已经这样做了。
  2. 使用 sscanf() 解析行。

使用 sscanf(),解析出四个字段是一个函数调用:

char name[16];
int num1, num2, num3;

if(sscanf(line, "%15s,%d,%d,%d", name, &num1, &num2, &num3) == 4)
{
printf("got '%s' with values %d, %d and %d\n", name, num1, num2, num3);
}

我不能 100% 确定您期望的字段是否正确,我发现您的描述(和代码)有点难以理解。我假设一个字符串后跟四个整数。

请注意,上面将字符串部分视为简单字符串;它不能嵌入空格。要改为依靠逗号分隔字段,请使用:

if(sscanf(line, "%15[^,],%d,%d,%d", name, &num1, &num2, &num3) == 4)
^
|
changed this

这会将第一部分视为一串非逗号字符,允许嵌入空格。

关于解析文件的C程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22063395/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com