开发者

Access a cell directly in .csv file using C programming

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?


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.


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.


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:

  • ccsv

And not many others in plain c. There are quite a few c++ implementations, and most of the are probably readily adapted to c.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜