Hello again everyone, Im having trouble with this function for saving a file from a richedit control within a child window in my application. I have put in extra messageboxes etc to helo me find the error. when I implement this function with valid parameters I recieve the "Invalid handle value" message box so I gathered that there is something wrong creating the handle to the file. However when I use this function for the first time for example when i create a file and save plain text into it, the function creats the file and writes to it successfully, but when i try again to save into this same file I recieve the "Invalid Handle Value" message. Here is the code for the function...
BOOL SaveFile(HWND owner,HWND hEdit, LPCTSTR pszFileName)
{
HANDLE hFile;
BOOL bSuccess = FALSE;
MessageBox(owner,pszFileName,0,0); // Testing if the parameter from pszFileName has been recieved
// Create the file (overwrite existing files) and assign the handle to hFile
hFile = CreateFile(pszFileName, GENERIC_WRITE, 0, NULL,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
//########## RETURNS INVALID HANDLE VALUE ############
//###### MAYBE PROBLEM WITH CREATING THE FILE ########
//####################################################
// If the handle to the file has been created sucessfully
if(hFile != INVALID_HANDLE_VALUE)
{
DWORD dwTextLength;
// Get text length of edit control within child window for allocating memory
dwTextLength = GetWindowTextLength(hEdit);
// If there is no text then there is nothing to write to the file that has been created
if(dwTextLength > 0)
{
LPSTR pszText;
// Amount of me mory to be allocated = textsize + 1 for null terminator
DWORD dwBufferSize = dwTextLength + 1;
// Allocate memory for the text
pszText = GlobalAlloc(GPTR, dwBufferSize);
if(pszText != NULL)
{
// Get the Text to be saved to the file fromt he edit control
// within the child window.
if(GetWindowText(hEdit, pszText, dwBufferSize))
{
DWORD dwWritten;
// Write the text to the file
if(WriteFile(hFile, pszText, dwTextLength, &dwWritten, NULL))
bSuccess = TRUE;
//Set Title of child window to the filename
SetWindowText(owner, pszFileName);
MessageBox(owner,"File saved",0,0); // Using to find error
}
else
{
MessageBox(owner,"Could not retrieve text",0,MB_ICONERROR); // Using to find error
}
// Free memory allocated for text
GlobalFree(pszText);
}
else
{
MessageBox(owner,"Could not allocate memory",0,MB_ICONERROR); // Using to find error
}
}
else
{
MessageBox(owner,"No text",0,0);// Using to find error
}
// Close the handle to the file if it exists
CloseHandle(hFile);
}
else
{
MessageBox(owner,"Invalid handle value",0,MB_ICONERROR); // Using to find error
}
return bSuccess;
}
Thanks in advance...