Retrieve value from CSV file
I want to as开发者_开发百科k, if there is any way, which I can retrieve the value of the first column in the last for, by using C programming.
Thanks!
Suppose my .csv file looks like this,
The fields are Item Number, Class Number and Supplier Number.
1111,1414,1000
1112,1010, 1001
1113,1112,1002
C code for reading values of above .csv file :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[])
{
if (argc < 2)
{
fprintf(stderr,"Usage: %s csv_file\n",argv[0]);
return(1);
}
FILE *f = fopen(argv[1], "rt");
char Line[256];
unsigned int AllocSize = 0, Size = 0, n;
char *L_text;
while(fgets(Line, sizeof(Line), f))
{
printf("Item = %s \n",strtok(Line, ", "));
printf("Class = %s \n",strtok(NULL, ", "));
printf("Supplier = %s \n",strtok(NULL, ", "));
}
return(0);
}
Maybe you can look at libcsv.
I think it depends on the size of your file. If the lines are not too big, there are not too many of them and you don't care if your program doesn't run with libcs other than GNU, you could use getline function to read entire lines into memory until you reach the last. Then it should be as simple as finding the first comma.
If you have a large file composed of small lines, you could fseek to the end of the file and back up byte per byte until you find a '\n'. Then you are at the beginning of the last line.
If both the file and lines are huge, perhaps doing a mmap on the entire file going to the end of it and then reading back to the '\n' might be more efficient than all those fseeks. Although mmap is arguably less portable than fseeks (since fseek is standard C).
精彩评论