Trying to append text to an edit control inside a dialog box. I can't get _tcscat_s to append correctly. It crashes and says something about the buffer being too small or something about a null terminated string.
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
return DialogBox( hInstance, MAKEINTRESOURCE( IDD_MAIN ), NULL, DlgProc );
}
BOOL CALLBACK DlgProc( HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam )
{
switch( Message )
{
case WM_INITDIALOG:
OpenAndReadFile( hwnd );
return TRUE;
case WM_COMMAND:
switch( LOWORD( wParam ) )
{
case IDSTART:
EndDialog( hwnd, IDSTART );
break;
case IDQUIT:
EndDialog( hwnd, IDQUIT );
break;
}
break;
case WM_CLOSE:
EndDialog( hwnd, 0 );
break;
default:
return FALSE;
}
return TRUE;
}
BOOL OpenAndReadFile( const HWND &hwnd )
{
// Open the file
HANDLE hFile;
hFile = CreateFile( TEXT( "sites.txt" ), // file to open
GENERIC_READ, // open for reading
FILE_SHARE_READ, // share for reading
NULL, // default security
OPEN_EXISTING, // existing file only
FILE_ATTRIBUTE_NORMAL, // normal file
NULL ); // no attr. template
if ( hFile == INVALID_HANDLE_VALUE )
{
SetDlgItemText( hwnd, IDC_OUTPUT, TEXT( "Error: File could not be opened\r\n" ) );
return FALSE;
}
else
SetDlgItemText( hwnd, IDC_OUTPUT, TEXT( "sites.txt opened\r\n" ) );
AppendText( hwnd, TEXT("TEXT") );
// Read data from file
const DWORD BUFFERSIZE = GetFileSize( hFile, NULL );
char *ReadBuffer = new char [BUFFERSIZE]();
DWORD dwBytesRead = 0;
// read one character less than the buffer size to save room for the
// terminate NULL character.
//if ( FALSE == ReadFile( hFile, ReadBuffer, BUFFERSIZE - 1, &dwBytesRead, NULL ) )
{
}
return TRUE;
}
void AppendText( const HWND &hwnd, TCHAR *newText )
{
// get size to determine buffer size
int outLength = GetWindowTextLength( GetDlgItem( hwnd, IDC_OUTPUT ) );
// create buffer to hold current text in edit control
TCHAR * buf = ( TCHAR * ) GlobalAlloc( GPTR, outLength + 1 );
// get existing text from edit control and put into buffer
GetDlgItemText( hwnd, IDC_OUTPUT, buf, outLength + 1 );
// append the newText to the buffer
_tcscat_s( buf, outLength + 1, newText );
// Set the text in the dialog
SetDlgItemText( hwnd, IDC_OUTPUT, buf );
}
std::string
, append to it, and save it back. In C++11 at least, the data is guaranteed to be contiguous. If not using C++11,std::vector
works almost just as well to load the text. Alternatively (and probably better), use this technique. No managing memory for it. No worries about appending. Just as easy to use. – Kordofan_tcscat_s()
DOES NOT grow the buffer if the appended text were to exceed the bounds of the buffer._tcscat_s()
has a parameter to specify the buffer size so it will truncate the concatenated text if it becomes too long. As such, you need to allocate the buffer to the required final size before you start putting text into it. – Trombidiasis