使用 C 编程直接访问 .csv 文件中的单元格
嘿伙计们! 有没有办法使用 C 直接访问 .csv 文件格式的单元格? 例如,我想使用 C 来总结一列,我该怎么做?
hey guys!
is there any way of directly accessing a cell in a .csv file format using C?
e.g. i want to sum up a column using C, how do i do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为此,使用
scanf
系列可能是最简单的,但这在一定程度上取决于数据的组织方式。假设您有三列数字数据,并且您想要对第三列求和,您可以循环执行如下语句:(file
is aFILE*
,并使用fopen
打开,循环直到到达文件末尾)并对
n
求和。如果文件中有其他类型的数据,则需要相应地指定格式字符串。如果不同的行具有不同类型的数据,您可能需要在字符串中搜索分隔符并选择第三个间隔。也就是说,根本不使用 C 可能更容易,例如 perl 或 awk 可能会做得更好,:) 但我认为这不是一个选择。
It's probably easiest to use the
scanf
-family for this, but it depends a little on how your data is organized. Let's say you have three columns of numeric data, and you want to sum up the third column, you could loop over a statement like this: (file
is aFILE*
, and is opened usingfopen
, and you loop until end of file is reached)and sum up the
n
s. If you have other kinds of data in your file, you need to specify your format string accordingly. If different lines have different kinds of data, you'll probably need to search the string for separators instead and pick the third interval.That said, it's probably easier not to use C at all, e.g. perl or awk will probably do a better job, :) but I suppose that's not an option.
如果您必须使用 C:将整行读取到内存中,请继续计算“,”,直到到达所需的列,读取该值并将其求和,然后转到下一行。
当达到你的值时,你可以使用 sscanf 来读取它。
If you have to use C: read the entire line to memory, go couting "," until you reach your desired column, read the value and sum it, go to next line.
When you reach your value, you can use sscanf to read it.
您可能需要首先查看 RFC 4180:逗号分隔值的通用格式和 MIME 类型 ( CSV)文件,然后寻找相同的实现。 (但请注意,逗号分隔值的概念早于 RFC,并且有许多实现不符合该文档。)
我发现:
纯 c 中的其他方法不多。有相当多的 C++ 实现,其中大多数可能很容易适应 C。
You might want to start by looking at RFC 4180: Common Format and MIME Type for Comma-Separated Values (CSV) Files, and then looking for implementations of the same. (Be aware though, that the notion of comma separated values predates the RFC and there are many implementations that do not comply with that document.)
I find:
And not many others in plain c. There are quite a few c++ implementations, and most of the are probably readily adapted to c.