Hi guys,
Is there any way to check the EOF in a .csv formatted file?
I don't think .csv files put an EOF statement at the end,so how are we supposed to search through the file without the EOF statement?
Thanks in advance
Hi guys,
Is there any way to check the EOF in a .csv formatted file?
I don't think .csv files put an EOF statement at the end,so how are we supposed to search through the file without the EOF statement?
Thanks in advance
EOF isn't stored in the file, so there is nothing to read.
Simply use
Code:while ( fgets(buff,sizeof(buff),fin) != NULL ) { // you got a line, search out all the commas }
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
thanks for that
I am trying to extract a particular column from the csv file and store it into an array.Any idea on how to efficiently do it?
Code - functions and small libraries I use
It’s 2014 and I still use printf() for debugging.
"Programs must be written for people to read, and only incidentally for machines to execute. " —Harold Abelson
CSV data files have variable field lengths (thus the need for the comma to mark the end of the field). Best way I know of is to count the comma's to your desired column number - 1, and then get your data. I don't believe it will make any difference whether you use a buffer to load your records into, and then extract the data from each field that you want, or whether you work directly from the file. Either way you'll be working with a buffer "under the hood" of the HD and operating system.
Given all that, using fgets() to get each row (and I'm assuming that one row of data will contain one record), sounds like a good way to go. Then use strchr() to find (and increment your counter), for each comma. With the general logic of:
Code:while(you have more records to read get one record with fgets(buffer, sizeofbuffer, pf)) { count=0 while(count<ColumnNumberYouWant -1) { char *p = strchr(buffer, ','); if(p) { ++count; }else break //there are no more comma's in this record } //read in your data and process it //start reading data from ++p, instead of buffer[0]. p is at the comma, //so you want to start at one char more }
Counting commas might work as a quick hack if you're fortunate enough to never have any commas or newlines within double-quotes in a column, but in general that is a broken solution.
You should parse the data properly. Read Comma-separated values - Wikipedia, the free encyclopedia and make sure the example in there can be parsed by your parser.
My homepage
Advice: Take only as directed - If symptoms persist, please see your debugger
Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"