简体   繁体   中英

Read .CSV file contents in MFC

Hi everyone I am a C++ MFC beginner and I want some help about how to read a .CSV file contents in C++ MFC by inherited the CStdioFile class.

the file has data like that:

AAAAAAAAA;BBBBBBB;CCCCCCC;DDDDDDDD; EEEEEEEE;FFFFFFFF; etc...

AAAAAAAA is directly the string without the "" for example like: test1;test2;...

and represent values in a excel in reality.

What I want is to create a new reader function with two parameters(line and column) that read into the file and extracts the good value and return it as a CString

For the moment this is the piece of code I have:

CString ReadData(int rl, int rc)
{
    CString sLine;
    LPCTSTR p = sLine;
    unsigned int i=1;
    unsigned int j=1;
    CString s;

    while(*p!= EOF)
    {
        if(*p==';' && i==rl)
            s.AppendChar(*p);
        if(*p=='\n')
            i++;
        p++;
    }
    return s;
}

This is not working and not finished yet.

What I want is some help to know a method to do that in the file, how to detect the end of the file( it is the EOF value normally ?), an end of line( '\\n' ?), Do I have to stock the differents strings in one line ? and of course some help in the code is also welcome.

Reading the file one character at a time is slow, you can read in larger blocks in to one string. This works as long as file is not too large. Then tokenize that string in to different lines, and tokenize each line in to different fields.

By the way, you are asking for "semi-colon separated value" not csv, so change ',' to ';'

void tokenize(vector<CStringA> &v, const CStringA &source, char token)
{
    for (int start = 0, len = source.GetLength(); start < len;)
    {
        int end = source.Find(token, start);
        if (end < 0) end = len;
        v.push_back(source.Mid(start, end - start));
        start = end + 1;
    }
}

void foo()
{
    CStringA source; //read the whole file in to one string "source"
    const int bufsize = 512 + 1;
    char buf[bufsize];
    CFile file("files.csv", CFile::modeRead|CFile::typeBinary);
    int count;
    while ((count = file.Read(buf, bufsize - 1)) > 0) {
        buf[count] = 0;
        source += buf;
    }

    source.Remove('\r');
    vector<CStringA> lines; //tokenize in to separate lines and store in vector
    tokenize(lines, source, '\n'); 

    for (int row = 0; row < (int)lines.size(); row++) {
        vector<CStringA> fields; //tokenize in to different fields
        tokenize(fields, lines[row], ',');
        for (int column = 0; column < (int)fields.size(); column++)
            TRACE("%s|", fields[column]); //print each field for testing
        TRACE("\n");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM