How to read/write a file

11 02 2012

Reading the contents of a file or writing to a file is common in any kind of applications. So how to open and close files as well as read and write to those files.

MFC provides a class CStdioFile to perform read/write operations from/to a file. This is a CFile derived class and the base class function Open would open an existing file or create a new file as per the flag uses in the second parameter of this function.
CStdioFile has two separate functions ReadString and WriteString to perform read and write operations respectively. Each functions read/write a single line of text.

  

//Create a new file

void WriteToFile()
{
	CStdioFile writeToFile;
	CFileException fileException;
	CString strFilePath = _T("C:\\Test.txt");

	if (writeToFile.Open( strFilePath, CFile::modeCreate|CFile::modeWrite), &fileException)
	{
		writeToFile.WriteString(_T("Hello\n"));
		writeToFile.WriteString(_T("Hi\n"));
		writeToFile.WriteString(_T("Bye\n"));
	}
	else
	{
		CString strErrorMsg;
		strErrorMsg.Format(_T("Can't open file %s , error : %u"), strFilePath, fileException.m_cause);
		AfxMessageBox(strErrorMsg);
	}

	writeToFile.Close();
}

//Read the contents of a file

void ReadFile()
{
	CStdioFile readFile;
	CFileException fileException;
	CString strFilePath = _T("C:\\Test.txt");
	CString strLine;

	if (readFile.Open(strFilePath, CFile::modeRead, &fileException))
	{
		while (readFile.ReadString(strLine));
	}
	else
	{
		CString strErrorMsg;
		strErrorMsg.Format(_T("Can't open file %s , error : %u"), strFilePath, fileException.m_cause);
		AfxMessageBox(strErrorMsg);
	}

	readFile.Close();
}

CFile is the base class for MFC file classes.It directly supports memory files and text files streaming through its derived classes.

Advertisements

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: