+ Reply to Thread
Results 1 to 3 of 3

Thread: how to read comma seperated file using CFile

  1. #1
    Junior Member
    Join Date
    Jun 2012

    how to read comma seperated file using CFile

    i was given a file, each line contains user name, real name, email...etc. all seperated by comma
    some other file i will be getting will have the pipe character between them

    i am trying to read using the CFile class, so far i got lines and lines of code just to seperate each item in the list using seek();
    is there any easier option like read line by line
    because in my project, i will get different files and each will have different character as seperator,
    thank you guys in advance

  2. #2
    Junior Member
    Join Date
    Jun 2012
    back in the time of stdio.h C programmers had access to every bit of the file
    luckily MFC added an alternative to CFile (although CFile is the recommended one for reading and writing file) the class is CStdioFile
    so declare your class
    CStdioFile MyFile;
    and simply use the very handy ReadString function from it
    this will read a single line from the file and stops at /n
    for your items that you need to separate
    try this code, i am assuming here that you have the pipe character as a seperator

    CAtlString str(strLine);
    curPos = 0;
    if(strLine.GetLength() == 0)
    strName = str.Tokenize(_T("|"),curPos);
    strUserName = str.Tokenize(_T("|"), curPos);
    strEmail = str.Tokenize(_T("|"), curPos);
    m_UsersList.InsertItem(j, strName);
    m_UsersList.SetItemText(j, 1, strUserName);
    m_UsersList.SetItemText(j, 2, strEmail);
    i hope that helped ,i was never good at teaching c++ but i always manage to get the code right

  3. #3
    Junior Member
    Join Date
    Jun 2012
    i assumed you were going to declare a CString for the file path
    CString strFilePath = _T("C:\\myfile.txt");

    //And another string to temporarily hold every line we read
    CString strLine;

    //Then use the Open function of the CStdioFile class
    //it takes three parameters, the path to the file in string format, the mode (in this case read only), and a pointer to the exception object
    // in case you want to handle exceptions later (use try and catch they are useful if you don't want your program to crash )
    MyFile.Open(strFilePath, CFile::modeRead, &fileException);

+ Reply to Thread


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts