| | |
Windows programming - C - Save file function
Please support our C++ advertiser: Intel Parallel Studio Home
Thread Solved |
•
•
Join Date: Aug 2005
Posts: 188
Reputation:
Solved Threads: 3
Ok I will post all of the code i have been using for saving the files...
This is the WM_COMMAND Message processing for saving files for the MDIClient...
This is the SaveFile function...
Finally this is the SaveFileAs Function...
As you can see the WM_COMMAND Message for the MDIClient procedure attempts to create a handle to an existing file..not overwriting! If the file exists the handle is created successfully which is then checked further down. If the file exists, the SaveFile function is called directly, using the WindowText of the ChildWindow as the Filename parameter and if the file does not exist, the SaveFileAs function is called. This basically does what most Text Editors do, decides whether to automatically save the file using its current filename or save the file as the user specifies...
When the user chooses to SaveFileAs...or the program decides that function is to be used, it works fine...the correct dialog appears and and prompts the user to overwrite existing files etc. The SaveFileAs function as you can see calls the SaveFile function and specifies the owner window parameter, the richedit control handle parameter and the filename specified by the user. THIS WORKS FINE !
My problem however is that when the file exists already and the user clicks save, the program takes the current filename of the file from the Title of the Child window and uses this as the FileName parameter. When this method is taken the error is generated. GetLastError() shows me what I have described above that the file is being used by another process etc.
Since when the SaveFile() function is called by the SaveFileAs() function and works correctly, I dont think there can be a problem with SaveFile(). So therefore I think there is something wrong with when I am passing the parameters to SaveFile() straight from the WM_COMMAND processing of the MDI Client.
Thanks for your help...tough 1
This is the WM_COMMAND Message processing for saving files for the MDIClient...
C++ Syntax (Toggle Plain Text)
case CM_FILE_SAVE: { LPSTR WindowText; DWORD dwTextLength; dwTextLength = GetWindowTextLength(hwnd); if (dwTextLength > 0) { DWORD dwBufferSize; dwBufferSize = dwTextLength + 1; WindowText = GlobalAlloc(GPTR, dwBufferSize); if(WindowText != NULL) { if ( ! GetWindowText(hwnd, WindowText, dwBufferSize) ) { MessageBox(hwnd,"Error Getting window text",0,MB_ICONERROR); } } else { MessageBox(hwnd,"Error allocating memory for text",0,MB_ICONERROR); } } else { MessageBox(hwnd,"No Window text",0,MB_ICONERROR); } // Text of the child window is retrieved correctly !! HANDLE hFile; hFile = CreateFile(WindowText, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); if (hFile != INVALID_HANDLE_VALUE) { if ( ! SaveFile(hwnd,GetDlgItem(hwnd,IDC_CHILD_EDIT),WindowText) ) { MessageBox(hwnd,"Could not save file",0,MB_ICONERROR); } } else { if ( ! SaveFileAs(hwnd,GetDlgItem(hwnd,IDC_CHILD_EDIT))) { MessageBox(hwnd,"Could not save file",0,MB_ICONEXCLAMATION); } } CloseHandle(hFile); SendDlgItemMessage(hwnd,IDC_CHILD_EDIT,EM_SETMODIFY,FALSE,0); } break; case CM_FILE_SAVEAS: { SaveFileAs(hwnd,GetDlgItem(hwnd,IDC_CHILD_EDIT)); SendDlgItemMessage(hwnd,IDC_CHILD_EDIT,EM_SETMODIFY,FALSE,0); } break;
This is the SaveFile function...
C++ Syntax (Toggle Plain Text)
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 { ShowLastError ( ) //Function calls GetLastError and then displays the error in a MessageBox MessageBox(owner,"Invalid handle value",0,MB_ICONERROR); // Using to find error } return bSuccess; }
Finally this is the SaveFileAs Function...
C++ Syntax (Toggle Plain Text)
BOOL SaveFileAs(HWND owner,HWND hwnd) { BOOL RetVal = FALSE; char szFile[MAX_PATH]; OPENFILENAME sfn; ZeroMemory(&sfn, sizeof(sfn)); sfn.lStructSize = sizeof(sfn); sfn.hwndOwner = hwnd; sfn.lpstrFile = szFile; // // Set lpstrFile[0] to '\0' so that GetOpenFileName does not // use the contents of szFile to initialize itself. // sfn.lpstrFile[0] = '\0'; sfn.nMaxFile = sizeof(szFile); sfn.lpstrFilter = "C Source File(*.c*)\0*.c;\0C++ Source File(*.cpp*)\0*.cpp;\0C Header File(*.h*)\0*.h;\0Resource Script(*.rc*)\0*.rc;\0"; sfn.nFilterIndex = 1; sfn.lpstrFileTitle = NULL; sfn.nMaxFileTitle = 0; sfn.lpstrInitialDir = NULL; sfn.Flags = OFN_SHOWHELP | OFN_OVERWRITEPROMPT; sfn.lpstrDefExt = "c"; GetSaveFileName(&sfn); if (SaveFile(owner,hwnd,szFile)) { RetVal = TRUE; } return RetVal; }
As you can see the WM_COMMAND Message for the MDIClient procedure attempts to create a handle to an existing file..not overwriting! If the file exists the handle is created successfully which is then checked further down. If the file exists, the SaveFile function is called directly, using the WindowText of the ChildWindow as the Filename parameter and if the file does not exist, the SaveFileAs function is called. This basically does what most Text Editors do, decides whether to automatically save the file using its current filename or save the file as the user specifies...
When the user chooses to SaveFileAs...or the program decides that function is to be used, it works fine...the correct dialog appears and and prompts the user to overwrite existing files etc. The SaveFileAs function as you can see calls the SaveFile function and specifies the owner window parameter, the richedit control handle parameter and the filename specified by the user. THIS WORKS FINE !
My problem however is that when the file exists already and the user clicks save, the program takes the current filename of the file from the Title of the Child window and uses this as the FileName parameter. When this method is taken the error is generated. GetLastError() shows me what I have described above that the file is being used by another process etc.
Since when the SaveFile() function is called by the SaveFileAs() function and works correctly, I dont think there can be a problem with SaveFile(). So therefore I think there is something wrong with when I am passing the parameters to SaveFile() straight from the WM_COMMAND processing of the MDI Client.
Thanks for your help...tough 1
Last edited by bops; Feb 14th, 2006 at 9:36 am. Reason: Missed something out.
Okay. Got it. You are trying to open the same file twice.
Here are the culprits.
Did you get where you are going wrong? You can fix it with a crude fix like this.
As I said that was a Crude Fix. Basically your design is wrong. That was why the error occured in the first place.
The Better Pseudocode will be something like this.
Global Variable FileName
On FileSave
Here are the culprits.
case CM_FILE_SAVE:
{
//...
HANDLE hFile;
hFile = CreateFile( WindowText, GENERIC_READ, FILE_SHARE_READ, NULL,
OPEN_EXISTING, 0, NULL );
// This function is successfull only when there is a file of name WindowText.
if ( hFile != INVALID_HANDLE_VALUE )
{
// YOu are here because hFile is valid. i.e the File is open.
// Now you are calling save File. Go to the SaveFile now.
if ( !SaveFile( hwnd, GetDlgItem( hwnd, IDC_CHILD_EDIT ), WindowText ))
{
MessageBox( hwnd, "Could not save file", 0, MB_ICONERROR );
}
}
else
{
//...
}
}
BOOL SaveFile( HWND owner, HWND hEdit, LPCTSTR pszFileName )
{
HANDLE hFile;
// We are here because hFile was valid. ie a File of pszFileName is open already. But you call CreateFile again.
// Try to create a file of name pszFileName...
hFile = CreateFile( pszFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL, NULL );
// But we had opened it before calling this function remember?
// Therefore this hFile should be Invalid with Access Error.
if ( hFile != INVALID_HANDLE_VALUE )
{
// Will not go here if the file exists...
}
else
{
}
return bSuccess;
}Did you get where you are going wrong? You can fix it with a crude fix like this.
case CM_FILE_SAVE:
{
//...
HANDLE hFile;
hFile = CreateFile( WindowText, GENERIC_READ, FILE_SHARE_READ, NULL,
OPEN_EXISTING, 0, NULL );
// This function is successfull only when there is a file of name WindowText.
if ( hFile != INVALID_HANDLE_VALUE )
{
// YOu are here because hFile is valid. i.e the File is open.
// Crude Fix - Close the file :-)
CloseHandle( hFile );
// Now you are calling save File. Go to the SaveFile now.
if ( !SaveFile( hwnd, GetDlgItem( hwnd, IDC_CHILD_EDIT ), WindowText ))
{
MessageBox( hwnd, "Could not save file", 0, MB_ICONERROR );
}
}
else
{
//...
}
}
BOOL SaveFile( HWND owner, HWND hEdit, LPCTSTR pszFileName )
{
HANDLE hFile;
// We are here because hFile was valid. ie a File of pszFileName is open already. But you call CreateFile again.
// Try to create a file of name pszFileName...
hFile = CreateFile( pszFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL, NULL );
// Thank god we closed the file.
if ( hFile != INVALID_HANDLE_VALUE )
{
//...
}
else
{
}
return bSuccess;
}As I said that was a Crude Fix. Basically your design is wrong. That was why the error occured in the first place.
The Better Pseudocode will be something like this.
Global Variable FileName
On FileSave
On FileSaveAs
if ( FileName not NULL )SAve to FileNameelseShow File Save AsClose FileName
Assign Value for FileName
Save to FileName
Show Save As Dialog
Assign value to FileName
Save To FileName
Close FileName
•
•
•
•
I thought that I wouldnt have to close the handle to the file if hFile = INVALID_HANDLE_VALUE
C++ Syntax (Toggle Plain Text)
hFile == INVALID_HANDLE_VALUE
C++ Syntax (Toggle Plain Text)
if ( hFile != INVALID_HANDLE_VALUE ) { ...
![]() |
Other Threads in the C++ Forum
- Previous Thread: reading a key without stoping the loop
- Next Thread: find strings in file.txt
| Thread Tools | Search this Thread |
Tag cloud for C++
api application array arrays assignment beginner binary bitmap c++ c/c++ calculator char char* class classes code coding compile compiler console conversion convert count data database delete developer display dll email encryption error file forms fstream function functions game generator getline givemetehcodez graph homeworkhelper iamthwee ifstream image input int java lazy lib loop looping loops map math matrix memory multidimensional multiple newbie news node number numbertoword output parameter pointer problem program programming project proxy python random read recursion recursive reference return sorting string strings struct template templates text tree url variable vector video visual visualstudio win32 windows winsock word wordfrequency wxwidgets






I didnt realise that...I thought that I wouldnt have to close the handle to the file if hFile = INVALID_HANDLE_VALUE, but i suppose it would be better to do that just to avoid errors. Anyway thanks a lot, it is very much appreciated.
