Click here to Skip to main content
15,894,343 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
How to read and display .txt file on client area in vc++ mfc?
Posted
Comments
Albert Holguin 29-Mar-11 0:08am    
this question is pretty simple... not going to try google first?

Hello,
First, you need to read the text from the file. One way to do this would be to use the CFile class to open and read the file data.
CFile file;
CFileException ex;
CString fileText;
// open the source file for reading
if (!file.Open(_T("Hello.txt"),
    CFile::modeRead | CFile::shareDenyWrite, &ex))
{
  // complain if an error happened
  // no need to delete the ex object
  TCHAR szError[1024];
  ex.GetErrorMessage(szError, 1024);
  TRACE1("Couldn't open source file: %s\n", szError);
}
else
{
  UINT nBytes = (UINT)file.GetLength();
  int nChars = nBytes / sizeof(TCHAR);
  nBytes = file.Read(fileText.GetBuffer(nChars), nBytes);
  fileText.ReleaseBuffer(nChars);
}

Then you have a few options for displaying the text.
If you are working on a dialog app the easiest thing might be to add a static control to the dialog and just set the text for the window
C#
CWnd *pwndStatic = this->GetDlgItem(IDC_LABEL);
if (pwndStatic)
{
    pwndStatic->SetWindowText(m_fileText);
}

Or, if you are trying something more sophisticated you can override the OnPaint method for the window you want the text in and draw the text yourself:
CPaintDC dc(this);
CRect rect;
GetClientRect(&rect);
dc.DrawText(m_fileText, &rect, DT_LEFT | DT_NOCLIP);

Hope this helps!
 
Share this answer
 
Hints for you.
Use CFile, open .txt file in read mode, read the text using Read() and display where you want.
 
Share this answer
 
Comments
Member 12374036 7-Mar-16 5:18am    
How to diaplay in other controls
My solution from me:
{
long lSize;
char * buffer;
size_t result;

pFile = fopen ( "C:\\examan.txt" , "rb" );
if (pFile==NULL) {fputs ("File error",stderr); exit (1);}

// obtain file size:
fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);

// allocate memory to contain the whole file:
buffer = (char*) malloc (sizeof(char)*lSize);
if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}

// copy the file into the buffer:
result = fread (buffer,1,lSize,pFile);
if (result != lSize) {fputs ("Reading error",stderr); exit (3);}

/* the whole file is now loaded in the memory buffer. */
UpdateData(true);
Edit1=buffer;
UpdateData(false);
// terminate
fclose (pFile);
free (buffer);
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900