Go Premium for a chance to win a PS4. Enter to Win

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
?
407 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: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
Technology Partners: 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 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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Have you tried to learn about Unicode, UTF-8, and multibyte text encoding and all the articles are just too "academic" or too technical? This article aims to make the whole topic easy for just about anyone to understand.
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.
Suggested Courses

926 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