使用 C 编程直接访问 .csv 文件中的单元格

发布于 2024-10-29 09:15:33 字数 65 浏览 1 评论 0原文

嘿伙计们! 有没有办法使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

旧情勿念 2024-11-05 09:15:33

为此,使用 scanf 系列可能是最简单的,但这在一定程度上取决于数据的组织方式。假设您有三列数字数据,并且您想要对第三列求和,您可以循环执行如下语句:(file is a FILE*,并使用 fopen 打开,循环直到到达文件末尾)

int n; fscanf(file, "%*d,%*d,%d", &n);

并对 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 a FILE*, and is opened using fopen, and you loop until end of file is reached)

int n; fscanf(file, "%*d,%*d,%d", &n);

and sum up the ns. 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.

隐诗 2024-11-05 09:15:33

如果您必须使用 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.

万人眼中万个我 2024-11-05 09:15:33

您可能需要首先查看 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文