如何最好地解析CSV数据文件并在C中进行查找? [英] How to best parse a CSV data file and do a lookup in C?

查看:46
本文介绍了如何最好地解析CSV数据文件并在C中进行查找?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我将拥有的文件数据类型示例:


Apple,4322,3435,4653,6543,4652

香蕉,6934,5423,6753,6531

Carrot,3454,4534,3434,1111,9120,5453

Cheese,4411,5522,6622,6641

第一个位置是我想要检索

对应代码的信息(产品)。假设每个产品的代码都是唯一的,并且所有代码数据都在一行上。


所以 - 我知道代码是''9120''我想逐行读取文件

并为逗号分隔的每一行构建一个数组。


有没有简单的方法来执行此操作一个库或者其他东西已经用于读取简单数据文件了吗?


尝试将我的perl代码转换为C ...


在Perl中这将是大约10行〜

$ prod_code =''9120'';


find_product( $ prod_code);


sub find_product {


$ find_code = shift;

foreach $ line(read_file( $ datafile)){

@data = split /,/,$ line; #将行拆分为数组

foreach $ code(@data){

#从元素列表中找到匹配

if( $ code == $ find_code){

返回$ data [0]; #返回列表中的第一个元素

}#end如果

} #end foreach

} #end foreach


} #end sub

我会想象这是经常做的事情

有一个库或一些已经构建的解决方案?但是我愿意用b $ b来学习如何用长C手来做这个......我只是不想重新发明

方向盘。


顺便说一句,我可以改变文件格式以适应更好的C解决方案如果

有一个? (即Apple = 1234,5677,3432)使用=而不仅仅是

第一个元素。


谢谢,


John

Here is an example of the type of data from a file I will have:

Apple,4322,3435,4653,6543,4652
Banana,6934,5423,6753,6531
Carrot,3454,4534,3434,1111,9120,5453
Cheese,4411,5522,6622,6641

The first position is the info (the product) I want to retreive for the
corresponding code. Assuming that the codes are unique for each product
and all code data is on one line.

So - I know the code is ''9120'' and I want to read the file line by line
and build an array for each line seperating on the commas.

Is there simple way to do this using a library or something already
created for reading simple data files?

Trying to convert from my perl code to C ...

In perl this would be about 10 or so lines...
$prod_code = ''9120'';

find_product($prod_code);

sub find_product {

$find_code = shift;
foreach $line (read_file($datafile)) {
@data = split /,/,$line; # split the line into an array
foreach $code (@data) {
# find a match from the list of elements
if ($code == $find_code) {
return $data[0]; # return the first element in the list
} # end if
} # end foreach
} # end foreach

} # end sub
I would imagine that this is something that is done often enough that
there is a library or some already built solution? But I am willing to
learn how to do this in long C hand... I just didn''t want to re-invent
the wheel.

BTW, I could change the file format to suit a better solution in C if
there is one? (i.e. Apple=1234,5677,3432) using the = instead of just
the first element.

Thanks,

John

推荐答案

prod_code =''9120'';


find_product(
prod_code = ''9120'';

find_product(


prod_code);


sub find_product {

prod_code);

sub find_product {


find_code = shift;

foreach
find_code = shift;
foreach


这篇关于如何最好地解析CSV数据文件并在C中进行查找?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆