home   articles   tags   browse code   

C++ CSV Parser


 

The function featured here is of course csvline_populate. It parses a line of data by a delimiter. If you pass in a comma as your delimiter it will parse out a Comma Separated Value (CSV) file. If you pass in a '\t' char it will parse out a tab delimited file (.txt or .tsv). CSV files often have commas in the actual data, but accounts for this by surrounding the data in quotes. This also means the quotes need to be parsed out, this function accounts for that as well.

It would make some sense to only pass in the line and delimiter to the function, and have the return type be the vector. However in terms of performance under heavy loads, this makes less sense. Passing in a predefined vector allows a function to populate it, copying bytes from your line as it goes. However, to not pass in a predefined vector, we'd have to declare it as a local variable to the function, which declares it on the stack. This means when the function completes, the variable will be deallocated, so when it returns the vector, the return keyword uses the copy constructor of the vector (which uses the copy constructor of each string object) to assign the return type to the variable in the caller function. To copy the return value of an object (depending on the size of your vector and the number of times you do it), can be an expensive operation.

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

void csvline_populate(vector<string> &record, const string& line, char delimiter);

int main(int argc, char *argv[])
{
    vector<string> row;
    string line;
    ifstream in("input.csv");
    if (in.fail())  { cout << "File not found" <<endl; return 0; }
     
    while(getline(in, line)  && in.good() )
    {
        csvline_populate(row, line, ',');
        for(int i=0, leng=row.size(); i<leng; i++)
            cout << row[i] << "\t";
        cout << endl;
    }
    in.close();
    return 0;
}

void csvline_populate(vector<string> &record, const string& line, char delimiter)
{
    int linepos=0;
    int inquotes=false;
    char c;
    int i;
    int linemax=line.length();
    string curstring;
    record.clear();
       
    while(line[linepos]!=0 && linepos < linemax)
    {
       
        c = line[linepos];
       
        if (!inquotes && curstring.length()==0 && c=='"')
        {
            //beginquotechar
            inquotes=true;
        }
        else if (inquotes && c=='"')
        {
            //quotechar
            if ( (linepos+1 <linemax) && (line[linepos+1]=='"') )
            {
                //encountered 2 double quotes in a row (resolves to 1 double quote)
                curstring.push_back(c);
                linepos++;
            }
            else
            {
                //endquotechar
                inquotes=false;
            }
        }
        else if (!inquotes && c==delimiter)
        {
            //end of field
            record.push_back( curstring );
            curstring="";
        }
        else if (!inquotes && (c=='\r' || c=='\n') )
        {
            record.push_back( curstring );
            return;
        }
        else
        {
            curstring.push_back(c);
        }
        linepos++;
    }
    record.push_back( curstring );
    return;
}


Note:
The only other problem with this code here, is that the definition of a csv allows for the newline character '\n' to be part of a csv field if the field is surrounded by quotes. The csvline_populate function takes care of this properly, but the main function which calls csvline_populate doesn't handle it. The way the main function works is that the getline(in, line) function populates the next line of the file from the 'in' stream using '\n' as a delimiter. So, if there is a '\n' in the middle of the csv field, the getline(in,line) still treats it as an end of line character. Most CSV files do not have a \n in the middle of the field, so it is usually not worth worrying about.

If one were to fix this issue, it would be by making a fgetcsv type function which operates directly on the FILE* handle or the ifstream. The function would also have to detect EOF (end of file).
 

Tags: c++
 
Jason Anderson on Apr 8th, 2009 9:14 pm said:
Hey, Awesome function, but you can remove the "int i;" line because i is not used. Just a FYI.
 

milkplus on Dec 14th, 2009 5:21 pm said:
very clean and excellent parser! one issue i saw was leading and trailing whitespace on the row strings is not trimmed off.
 

Roberto on Mar 3rd, 2010 5:01 am said:
Nice~
 

Roberto on Jul 7th, 2010 5:50 pm said:
I believe a far more efficient C++ CVS implementation can be found here: http://www.codeproject.com/KB/recipes/Tokenizer.aspx
 

Lis on Dec 18th, 2010 8:53 am said:
Well the above lib makes heavy use of boost. While this is just a simple 50 line function. Great work.
 

Jeff B on Apr 18th, 2011 11:29 pm said:
Great little function. So simple.
 

Bernard on May 30th, 2011 8:40 am said:
Nice. Thanks.
 

Runia on Jun 5th, 2011 11:33 am said:
Thank you for sharing the csv parser. It works perfectly. Maybe http://www.codeproject.com/KB/recipes/Tokenizer.aspx is more efficient and the ideas behind are nice but it is not as easily applied neither does it yield immediate results like your code. Thank you.
 

Jan on Feb 22nd, 2013 2:53 am said:
I'm sorry to say, but it does not work for multiple quoted fields. Like "Aaaa", "Bbbb"
 



 

 



Related Articles
 


home  |  privacy policy  |  terms of use  |  contact  


©2013, Zedwood.com

zedwood.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to amazon.com