OPENFILENAME open dialog - c++

i want to get a full file path by open file dialog in win32.
i do it by this function:
string openfilename(char *filter = "Mission Files (*.mmf)\0*.mmf", HWND owner = NULL) {
OPENFILENAME ofn ;
char fileName[MAX_PATH] = "";
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(OPENFILENAME);
ofn.hwndOwner = owner;
ofn.lpstrFilter = filter;
ofn.lpstrFile = fileName;
ofn.nMaxFile = MAX_PATH;
ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
ofn.lpstrDefExt = "";
ofn.lpstrInitialDir ="Missions\\";
string fileNameStr;
if ( GetOpenFileName(&ofn) )
fileNameStr = fileName;
return fileNameStr;
}
it's work fine and return path . but i can't write into the that file i get path of it with openfilename.
note :
i call this code to write to the file (serialization):
string Mission_Name =openfilename();
ofstream ofs ;
ofs = ofstream ((char*)Mission_Name.c_str(), ios::binary );
ofs.write((char *)&Current_Doc, sizeof(Current_Doc));
ofs.close();

Try this for write:
string s = openfilename();
HANDLE hFile = CreateFile(s.c_str(), // name of the write
GENERIC_WRITE, // open for writing
0, // do not share
NULL, // default security
CREATE_ALWAYS, // Creates a new file, always
FILE_ATTRIBUTE_NORMAL, // normal file
NULL); // no attr. template
DWORD writes;
bool writeok = WriteFile(hFile, &Current_Doc, sizeof(Current_Doc), &writes, NULL);
CloseHandle(hFile);
... and read:
HANDLE hFile = CreateFile(s.c_str(), // name of the write
GENERIC_READ, // open for reading
0, // do not share
NULL, // default security
OPEN_EXISTING, // Creates a new file, always
FILE_ATTRIBUTE_NORMAL, // normal file
NULL); // no attr. template
DWORD readed;
bool readok = ReadFile(hFile, &Current_Doc, sizeof(Current_Doc), &readed, NULL);
CloseHandle(hFile);
Help links:
http://msdn.microsoft.com/en-us/library/windows/desktop/bb540534%28v=vs.85%29.aspx
http://msdn.microsoft.com/en-us/library/windows/desktop/aa363858%28v=vs.85%29.aspx

Try closing it and reopen then for writing.

Related

ifstream not opening filename from getopenfilename

Amateur programmer here. My problem today is that I am trying to load a .txt file in to be displayed in the edit box of a dialog box.
before I start with code: I can get it to work by SPECIFYING the file location and bypassing the load dialog from getopenfilename, and it works swimmingly. But when i obtain that file location from getopenfilename, i can't seem to work it.
The relevant code is:
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hDlg;
ofn.lpstrFile = szFile;
ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = sizeof(szFile);
ofn.lpstrFilter = "All\0*.*\0Text\0*.TXT\0";
ofn.nFilterIndex = 1;
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
if (GetOpenFileName(&ofn) == TRUE)
{
hf = CreateFile(ofn.lpstrFile, GENERIC_READ, 0, LPSECURITY_ATTRIBUTES)NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, (HANDLE)NULL);
ifstream inFile(ofn.lpstrFile);
if (!inFile)
MessageBox(0, "CAN'T OPEN FILE", "ALERT", MB_OK | MB_ICONWARNING);
else
{
string text;
while(getline(inFile, text));
inFile.close();
MessageBox(0, text.c_str(), "msg", MB_OK);
SetWindowText(editbox, text.c_str());
}
CloseHandle(hf);
hf = INVALID_HANDLE_VALUE;
I am a novice, but I have been wracking my brain and my google bar trying to figure this out.
It does not ever open via fstream.
The source of the problem is that you try to open the file with both Win32 API (CreateFile()) and with standard library (std::ifstream).
By looking at your CreateFile() call and at the documentation, one can see that you are passing 0 to the dwShareMode argument, whose description states:
If this parameter is zero and CreateFile succeeds, the file or device cannot be shared and cannot be opened again until the handle to the file or device is closed.
But, after that call, you proceed to try to open the file via std::ifstream, which fails due to the reason described above, and you are only checking if ifstream succeeds to open the file.
The issue can be avoided if you use only either CreateFile() or std::ifstream, not both.

C++ CreateFile cant read file ERROR_ACCESS_DENIED [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm trying to read file content, but despite it's able to write to same file. I can't read from it! The program is running as Adminstator.
I have Tried to give " FILE_SHARE_WRITE | FILE_SHARE_READ " rights, but still not work.
DWORD dwBytesWritten = 0;
unsigned long BytesRead = 0;
HANDLE hFile = INVALID_HANDLE_VALUE;
wchar_t text_file[MAX_PATH] = { 0 };
TCHAR *save_text(void) {
OPENFILENAME ofn = { 0 };
TCHAR filename[512] = _T("C://Windows/EXAMPLE.txt");
ofn.lStructSize = sizeof(ofn);
ofn.lpstrFilter = L"Txt files (*.txt)\0*.txt\0All Files\0*.*\0";
ofn.lpstrFile = filename;
ofn.nMaxFile = sizeof(filename);
ofn.Flags = OFN_NONETWORKBUTTON | OFN_OVERWRITEPROMPT | OFN_PATHMUSTEXIST | OFN_LONGNAMES | OFN_EXPLORER | OFN_HIDEREADONLY;
ofn.nFilterIndex = 1;
return(filename);
}
void WriteToFile(TCHAR *wText)
{
wchar_t loginchar[1000];
hFile = CreateFile(text_file, FILE_APPEND_DATA, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_HIDDEN, NULL);
WriteFile(hFile, wText, wcslen(wText) * sizeof(wchar_t), &dwBytesWritten, NULL); // its writing without problem
ReadFile(hFile, loginchar, wcslen(loginchar) * sizeof(wchar_t), &BytesRead, NULL); // accses denied
ResultInFile(GetLastError()); // ResultInFile funcitons writes paramater to the file
//ResultInFile(BytesRead); // to see how many bytes read, but of course doesnt work..
CloseHandle(hFile);
}
// this is the how file created at main function :
hFile = CreateFile(txt_file, FILE_APPEND_DATA, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_HIDDEN, NULL);
try:
hFile = CreateFile(text_file, FILE_APPEND_DATA | FILE_READ_DATA, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_HIDDEN, NULL);
instead of:
hFile = CreateFile(text_file, FILE_APPEND_DATA, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_HIDDEN, NULL);
Note that FILE_SHARE_READ allows other calls of CreateFile ask for read permissions, it does not affect the read permissions of your file handle.

Browsing for file location and saving wstring to file

I am trying to create a file dialog where the user selects an existing file or create a new one by selecting a location and entering a name. The browsing works fine, but when I try to save the file, it gives me the following error
fail: file != NULL.
I also have to convert the text that is meant to be written to the file from std::wstring to char *, hence the sprint. I can't figure out what I am doing wrong.
Below is the code I am currently working with:
HMODULE hModule = GetModuleHandleW(NULL);
OPENFILENAME ofn;
char szFile[260]; // buffer for file name
HWND hwnd = NULL; // owner window
HANDLE hf; // file handle
// Initialize OPENFILENAME
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hwnd;
ofn.lpstrTitle = TEXT("Select a location to save the information");
ofn.nMaxFile = sizeof(szFile);
ofn.lpstrFilter = TEXT("All\0*.*\0Text\0*.TXT\0");
ofn.nFilterIndex = 1;
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
if(GetSaveFileName(&ofn)==TRUE)
{
wchar_t hostName[2048] = L"";
DWORD sz = 2048;
hf = CreateFile(ofn.lpstrFile, GENERIC_READ,
0, (LPSECURITY_ATTRIBUTES)NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,
(HANDLE)NULL);
char * buffer = new char[242];
//sprintf(buffer, "%ls", hostInfo.c_str());
_snprintf_s(buffer,242, _TRUNCATE, "%ls", hostInfo.c_str());
std::ofstream stream(ofn.lpstrFile, std::ofstream::binary);
stream.write(buffer, 243);
//delete[] buffer;
stream.close();
}
EDIT:
Found the problem. I did not set the pointer for lpstrFile resulting in the selected path being NULL hence the File != NULL assert fail

Strange behaviour with GetOpenFileName dialog and opencv

I'm trying to use the open file dialog to allow the user of my program to select an image which will then be processed using opencv.
I have a function in which i open the dialog and try to load the image:
Mat load_image()
{
OPENFILENAME ofn; // common dialog box structure
TCHAR szFile[260]; // buffer for file name
HWND hwnd; // owner window
HANDLE hf; // file handle
// Initialize OPENFILENAME
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hwnd;
ofn.lpstrFile = szFile;
// Set lpstrFile[0] to '\0' so that GetOpenFileName does not
// use the contents of szFile to initialize itself.
ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = sizeof(szFile);
ofn.lpstrFilter = L"All\0*.*\0Text\0*.TXT\0";
ofn.nFilterIndex = 1;
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
// Display the Open dialog box.
if (GetOpenFileName(&ofn)==TRUE)
hf = CreateFile(ofn.lpstrFile,
GENERIC_READ,
0,
(LPSECURITY_ATTRIBUTES) NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
(HANDLE) NULL);
char filepath[260];
wcstombs(filepath, ofn.lpstrFile, 260);
cout << filepath << endl;
Mat src = imread(filepath);
//imshow("src", src);
return src;
}
The code you see here works, opens the dialog box and allows the user to choose a file. The filepath is then converted to string (to be passed into imread). The problem occurs when I try to interact with the image src.
For example, if I uncomment the 'imshow' line, GetOpenFileName will return 0 and the dialog box doesnt even open. This happens more than not, I cant actually access the image because everything I try causes this to happen.
In order for the function to work it is called like this:
load_image();
But if I try to assign an image ie:
img = load_image();
the same problem occurs. Help! What could possibly be causing this?
As it is mentioned in the previous comment, the CreateFile method locks the image file so cv::imread() is not able to access/read its content.
Try to avoid using of CreateFile, I see no reason of using it in your code, the following code is working well:
cv::Mat load_image()
{
cv::Mat outMat;
OPENFILENAME ofn; // common dialog box structure
TCHAR szFile[260]; // buffer for file name
// Initialize OPENFILENAME
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = NULL;
ofn.lpstrFile = szFile;
ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = sizeof(szFile);
ofn.lpstrFilter = L"All\0*.*\0Text\0*.TXT\0";
ofn.nFilterIndex = 1;
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
// Display the Open dialog box.
if (GetOpenFileName(&ofn) == TRUE)
{
char filepath[260];
wcstombs(filepath, ofn.lpstrFile, 260);
cout << filepath << endl;
outMat = cv::imread(filepath);
}
return outMat;
}
int main()
{
cv::Mat image = load_image();
cv::imshow("image", image);
cv::waitKey(-1);
return 0;
}
These are just things I notice in your code...so I don't expect this to work but maybe it will help.
imread is probably failing. You opened the file using CreateFile and locked it as a result of opening it (No Sharing Attributes. See CreateFile for more info). imread tries to open the file anyways so you don't need to create your own handle! Just use the file path received and call imread instead of using CreateFile.
Mat src;
if (GetOpenFileName(&ofn)==TRUE)
{
// Succeeded in choosing a file
char filepath[260];
wcstombs(filepath, ofn.lpstrFile, 260);
cout << filepath << endl;
src = imread(filepath);
}
Also if you don't have an hwnd then you should just set ofn.hwndOwner=NULL instead of arbitrarily setting it.
If you so choose to use CreateFile (maybe you wish to open it for manual read access for your own purposes outside of OpenCV), then make sure to call CloseHandle( HANDLE h ) on the file handle before you open the file again.

GetOpenFileName triggers breakpoint

I'm trying to call GetOpenFileName like this:
int main(int argc, char* argv[])
{
OPENFILENAME ofn; // common dialog box structure
wchar_t szFile[260]; // buffer for file name
HWND hwnd; // owner window
HANDLE hf; // file handle
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
wchar_t title[500]; // to hold title
GetConsoleTitle( title, 500 );
HWND hwndConsole = FindWindow( NULL, title );
ofn.hwndOwner = hwndConsole;
ofn.lpstrFile = szFile;
ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = sizeof(szFile);
ofn.lpstrFilter = L"All\0*.*\0Text\0*.TXT\0";
ofn.nFilterIndex = 1;
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
// Display the Open dialog box.
if (GetOpenFileName(&ofn)==TRUE)
hf = CreateFile(ofn.lpstrFile,
GENERIC_READ,
0,
(LPSECURITY_ATTRIBUTES) NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
(HANDLE) NULL);
The prog stops (message: example.exe has triggered a breakpoint(not one I placed)) at "if (GetOpenFileName(&ofn)==TRUE)" When I break i get a message that no source is available.
If I do not break and just press continue, the dialog box pops up and works as expected. What am I doing wrong?
I just noticed that it works without problems in release mode...
One possible issue:
ofn.nMaxFile should be the number of characters, not the size in bytes of the buffer. Try this instead:
ofn.nMaxFile = sizeof(szFile) / sizeof(wchar_t);