Solved

Can someone provide me a sample to read a csv file into an array / simple code to write to a file

Posted on 2007-11-20
9
399 Views
Last Modified: 2013-11-20
MFC is new for me any help would be appreciated, I need some code to write a file with comma separated values and code to read the values into an array
0
Comment
Question by:JonMny
  • 3
  • 2
  • 2
  • +2
9 Comments
 
LVL 11

Expert Comment

by:DeepuAbrahamK
ID: 20322636
0
 
LVL 11

Expert Comment

by:DeepuAbrahamK
ID: 20322678
MFC Version:
http://www.codeproject.com/file/cdatafile.asp

Best Regards,
DeepuAbrahamK
0
 
LVL 86

Expert Comment

by:jkr
ID: 20322747
Could yo ube a bit more specific about what you want to store in that file and how the values that are read from it should be organized?
0
ScreenConnect 6.0 Free Trial

Explore all the enhancements in one game-changing release, ScreenConnect 6.0, based on partner feedback. New features include a redesigned UI, app configurations and chat acknowledgement to improve customer engagement!

 
LVL 9

Author Comment

by:JonMny
ID: 20325304
Sorry, I didn't give enough info, I need to write 3 string values to a file. Either a comma delimited file that I can read into an array. Or just three lines of text that I can read line by line.

The catch is this is a Unicode project so I can't use Cfile.

Example

ClientName,OrderNumber,OrderStatus

ClientName
OrderNumber
OrderStatus

Either is fine this is just a sample I am creating


0
 
LVL 4

Expert Comment

by:yuy2002
ID: 20326266
>>Example

>>ClientName,OrderNumber,OrderStatus

>>ClientName
>>OrderNumber
>>OrderStatus
implemetation by c





TCHAR srcStr[3][32];
	_tcscpy(srcStr[0],_T("ClientName"));
    _tcscpy(srcStr[1],_T("OrderNumber"));
	_tcscpy(srcStr[2],_T("OrderStatus"));
    
	FILE*   fp; 
	TCHAR* pFileName = _T("test.txt");
	fp = _tfopen(pFileName, _T("w+b"));
	int i;
	if(   fp   !=   NULL   )   
	{     
		const   BYTE   head[]   =   {0xff,   0xfe};//BOM(byte-order   mark)   
		fwrite(head,   sizeof(BYTE),   sizeof(head)/sizeof(BYTE),   fp);   
 
		for(i=0;i<3;i++)
		{
			
			fwrite(srcStr[i],   sizeof(TCHAR),   _tcslen(srcStr[i]),   fp);   
			fwrite(_T(","),sizeof(TCHAR),_tcslen(_T(",")),fp);
		}
	}  
	fclose(fp);  

Open in new window

0
 
LVL 4

Expert Comment

by:yuy2002
ID: 20326293
MFC implemetation.
CString srcStr[3];
	srcStr[0] = _T("ClientName");
	srcStr[1] = _T("OrderNumber");
	srcStr[2] = _T("OrderStatus");
 
	CFile file;
    LPCTSTR pFileName = _T("test.txt");
	if(!file.Open(pFileName,CFile::modeCreate | CFile::modeWrite))
	{
		//ERROR
	}
    const   BYTE   head[]   =   {0xff,   0xfe};//BOM(byte-order   mark)   
	file.Write(head,2);
	int i;
	for( i=0;i<3;i++)
	{
        file.Write(srcStr[i],sizeof(TCHAR)*srcStr[0].GetLength());
		file.Write(",",sizeof(TCHAR));
	}
    file.Close();

Open in new window

0
 
LVL 39

Accepted Solution

by:
itsmeandnobodyelse earned 500 total points
ID: 20326737
>>>> The catch is this is a Unicode project so I can't use Cfile.

If I am understanding that correctly the file should be single char (ANSI 8bit) while the  MFC uses UNICODE strings because of the project settings? If so, you can use the CStdioFile without problems. Look at the following excerpt from MSDN:

...............................................................................
When a Unicode stream I/O routine (such as fwprintf, fwscanf, fgetwc, fputwc, fgetws, or fputws) operates on a file that is open in text mode (the default), two kinds of character conversions take place:

Unicode-to-MBCS or MBCS-to-Unicode conversion. When a Unicode stream-I/O function operates in text mode, the source or destination stream is assumed to be a sequence of multibyte characters. Therefore, the Unicode stream-input functions convert multibyte characters to wide characters (as if by a call to the mbtowc function). For the same reason, the Unicode stream-output functions convert wide characters to multibyte characters (as if by a call to the wctomb function).
Carriage return – linefeed (CR-LF) translation. This translation occurs before the MBCS – Unicode conversion (for Unicode stream input functions) and after the Unicode – MBCS conversion (for Unicode stream output functions). During input, each carriage return – linefeed combination is translated into a single linefeed character. During output, each linefeed character is translated into a carriage return – linefeed combination.
However, when a Unicode stream-I/O function operates in binary mode, the file is assumed to be Unicode, and no CR-LF translation or character conversion occurs during input or output. Use the _setmode( _fileno( stdin ), _O_BINARY ); instruction in order to correctly use wcin on a UNICODE text file.

...............................................................................

The CStdioFile opens a file in text mode. According to the above docs it writes a ANSI text file then. (Don't be confused by the term 'multibyte characters'. Actually it is 8-bit single char). CStdioFile::WriteString uses _fputts to write the LPCTSTR argument to file. In case of a UNICODE project all input should be passed as UNICODE strings and were written as ANSI strings. With CStdioFile::ReadString it was made reversed.

>>>> BOM(byte-order   mark)
CStdioFile doesn't write a byte-order-mark. You shouldn't do it either beside you need some special byte conversion.

Note, the code of yuy2002 writes a BOM for UTF-16 what is a UNICODE text file. These text files cannot be opened by all text editors. It is *not* recommended to use that formatting beside your data were using the UNICODE char set.

....
#include <vector>    // std::vector
using namespace std;


struct Order
{
      CString strClientName;
      CString strOrderNumber;
      CString strOrderStatus;
};

// note, in a UNICODE project CString handles UNICODE strings

BOOL CMyDoc::WriteCSVFromOrders(const CString& strFilename, const vector<Order> orders)
{
     CStdioFile file;
     if (!file.Open(strFilename, CFile::modeCreate | CFile::modeWrite | CFile::typeText ))
     {
            AfxMessageBox(strFilename + " cannot be opened");
            return FALSE;
     }
     vector<Order>::const_iterator iter;
     for (iter = orders.begin(); iter != orders.end(); ++iter)
     {
            const Order& order = *iter;
            TRY
            {
                 file.WriteString(order.strClientName + _T(",") +
                                         order.strClientNumber + _T(",") +
                                        order.strOrderStatus + _T("\n"));
             }
             CATCH( CFileException, e )
             {
                   AfxMessageBox(strFilename + " error when writing");
                   file.Close();
                   return FALSE;
              }
              END_CATCH
      }
      file.Close();
      return TRUE;
}

Regards, Alex

0
 
LVL 9

Author Closing Comment

by:JonMny
ID: 31410200
Thanks for the help!
0
 
LVL 4

Expert Comment

by:yuy2002
ID: 20332394
itsmeandnobodyelse,thank u for your advice.
0

Featured Post

Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction: Finishing the grid – keyboard support for arrow keys to manoeuvre, entering the numbers.  The PreTranslateMessage function is to be used to intercept and respond to keyboard events. Continuing from the fourth article about sudoku. …
Introduction: Dialogs (2) modeless dialog and a worker thread.  Handling data shared between threads.  Recursive functions. Continuing from the tenth article about sudoku.   Last article we worked with a modal dialog to help maintain informat…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question