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

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
LVL 9
JonMnyAsked:
Who is Participating?
 
itsmeandnobodyelseCommented:
>>>> 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
 
Deepu AbrahamR & D Engineering ManagerCommented:
0
 
Deepu AbrahamR & D Engineering ManagerCommented:
MFC Version:
http://www.codeproject.com/file/cdatafile.asp

Best Regards,
DeepuAbrahamK
0
Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

 
jkrCommented:
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
 
JonMnyAuthor Commented:
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
 
yuy2002Commented:
>>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
 
yuy2002Commented:
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
 
JonMnyAuthor Commented:
Thanks for the help!
0
 
yuy2002Commented:
itsmeandnobodyelse,thank u for your advice.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.