Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
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
Medium Priority
?
404 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:Deepu Abraham
ID: 20322636
0
 
LVL 11

Expert Comment

by:Deepu Abraham
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
Will your db performance match your db growth?

In Percona’s white paper “Performance at Scale: Keeping Your Database on Its Toes,” we take a high-level approach to what you need to think about when planning for database scalability.

 
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 2000 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

Learn how to optimize MySQL for your business need

With the increasing importance of apps & networks in both business & personal interconnections, perfor. has become one of the key metrics of successful communication. This ebook is a hands-on business-case-driven guide to understanding MySQL query parameter tuning & database perf

Question has a verified solution.

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

When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
Introduction: Hints for the grid button.  Nested classes, templated collections.  Squash that darned bug! Continuing from the sixth article about sudoku.   Open the project in visual studio. First we will finish with the SUD_SETVALUE messa…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.
Suggested Courses

715 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