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
401 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Templates For Beginners Or How To Encourage The Compiler To Work For You Introduction This tutorial is targeted at the reader who is, perhaps, familiar with the basics of C++ but would prefer a little slower introduction to the more ad…
Introduction: Database storage, where is the exe actually on the disc? Playing a game selected randomly (how to generate random numbers).  Error trapping with try..catch to help the code run even if something goes wrong. Continuing from the seve…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

734 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