ifstream not opening filename from getopenfilename - c++

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.

Related

CopyFile API function not working after using GetOpenFileName to get the file path

I am using GetOpenFileName() to get the file path, and then CopyFile() to copy the file to the same directory with a different file name.
By using GetLastError(), I am getting an error code:
0x2 - The system cannot find the file specified.
But when I used MessageBox() to see the file names, it showed the correct file names.
In addition to this, I have also tried to StrTrim() the file name, but still it did not work.
I am using Borland C++Builder 6.0.
CODE
OPENFILENAME ofn;
char szFile[260];
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = Form1->Handle;
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 = 0;
GetOpenFileName(&ofn);
LPSTR FileName;
FileName = ofn.lpstrFile;
MessageBox (Form1->Handle, FileName, "File Name", MB_OK);
MessageBox (Form1->Handle, strcat(FileName, ".newfile"), "New File Name", MB_OK);
CopyFile(FileName, strcat(FileName,".newfile"), false);
EDITED CODE
I have tried using two variables, but it is still not working. Can anyone suggest a correction?
LPSTR FileName;
LPSTR NewFileName;
FileName = ofn.lpstrFile;
NewFileName = FileName;
strcat(NewFileName, ".newfile");
MessageBox (Form1->Handle, FileName, "File Name", MB_OK);
MessageBox (Form1->Handle, NewFileName, "New File Name", MB_OK);
CopyFile(FileName, NewFileName, false);
WORKING CODE
The below code works, but I had to add a Text Box / Edit Control. Is there way to do it without adding any extra control?
LPSTR FileName;
AnsiString NewFileName;
FileName = ofn.lpstrFile;
Edit1->Text = FileName;
NewFileName = Edit1->Text + ".bak";
MessageBox (Form1->Handle, FileName, "File Name", MB_OK);
MessageBox (Form1->Handle, NewFileName.c_str(), "New File Name", MB_OK);
You are using a single buffer for both arguments of CopyFile(), and you are appending the new extension to that buffer, so of course CopyFile() is not going to find the file to copy.
You need to use two separate buffers for the two arguments of CopyFile(), eg:
TCHAR szSrcFile[MAX_PATH];
TCHAR szDstFile[MAX_PATH+12];
OPENFILENAME ofn;
ZeroMemory(&ofn, sizeof(ofn)); ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = Form1->Handle;
ofn.lpstrFile = szSrcFile;
ofn.lpstrFile[0] = TEXT('\0');
ofn.nMaxFile = MAX_PATH;
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 (GetOpenFileName(&ofn))
{
lstrcpy(szDstFile, szSrcFile);
lstrcat(szDstFile, TEXT(".newfile"));
MessageBox(Form1->Handle, szSrcFile, TEXT("File Name"), MB_OK);
MessageBox(Form1->Handle, szDstFile, TEXT("New File Name"), MB_OK);
CopyFile(szSrcFile, szDstFile, FALSE);
}
That being said, since you are using Borland's VCL framework, you should use the TOpenDialog component instead of GetOpenFileName() directly, and then you can use String variables for easy concatenation:
// these properties can also be set at design-time instead...
OpenDialog1->Filter = "All|*.*|Text|*.txt";
OpenDialog1->FilterIndex = 1;
OpenDialog1->Options = TOpenOptions() << ofPathMustExist << ofFileMustExist;
if (OpenDialog1->Execute())
{
String SrcFile = OpenDialog1->FileName;
String DstFile = SrcFile + ".newfile";
CopyFileA(SrcFile.c_str(), DstFile.c_str(), FALSE);
}

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.

OPENFILENAME open dialog

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.

GetOpenFileName and system function call run time errors c++ win32 api

I've been working on a simple windows program using Visual C++ 2010 express on a 64bit Windows 7 machine. So far I have simple menu with and an editable text area. I'm trying to allow the user select a media file (movie or music file) and play it using the default program.
When the user selects from the menu File->Play->File from Computer it runs the following code.
case ID_PLAY_FFC:
{
system("cd c:/windows/system32/&&cmd.exe");
FileOpen(hWnd);
system("cd c:/windows/system32/&&cmd.exe");
}
break;
The problem is that the first system call runs as expected. The second call tells me that "cmd.exe is not recognized as an internal or external command, operable program, or batch file". I've tried placing the second system call within the File Open function and it seems to work anywhere before GetOpenFileName but not after.
The only thing I really need to get the is file path so I was wondering if any one knew how to fix this problem or a better way to accomplish this?
code for FileOpen():
void FileOpen(HWND hwnd)
{
OPENFILENAME ofn; // common dialog box structure
char szFile[MAX_PATH]; // buffer for file name MAX_PATH = 260
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 = "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.
//system("cd c:/windows/system32/&&cmd.exe"); will execute here.
if (GetOpenFileName(&ofn)==TRUE)
{
//system("cd c:/windows/system32/&&cmd.exe"); but not here.
hf = CreateFile(ofn.lpstrFile,
GENERIC_READ,
0,
(LPSECURITY_ATTRIBUTES) NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
(HANDLE) NULL);
if (hf == (HANDLE)-1)
{
MessageBox(NULL,"Could not open this file", "File I/O Error", MB_ICONSTOP);
return;
}
}
}
The GetOpenFileName() function changes the working directory and drive as part of it's operation. Your call to cd does not change the working drive and cmd.exe is still not in the working directory.
The solution depends on what exactly you're trying to do in the end, but you can specify the full path to cmd.exe (See the %COMSPEC% environment variable) and not rely on a command interpreter, or pass the OFN_NOCHANGEDIR flag to tell it not to clobber the working directory.
Note that there isn't any real reason for a (GUI) app to require a specific working path. You should fully qualify everything you can.
Calling system() starts a new process, so even if your cd commands were valid (which they are not), it would not matter because you would be changing the working directory of another process, not your app's process. To set the working directory of your app's process, use SetCurrentDirectory() instead of system(), eg:
case ID_PLAY_FFC:
{
SetCurrentDirectory(TEXT("c:/windows/system32/"));
FileOpen(hWnd);
SetCurrentDirectory(TEXT("c:/windows/system32/"));
}
break;
However, you don't need to do that manually because the OFN_NOCHANGEDIR flag of GetOpenFileName() automatically handles that internally for you. Whatever the calling process's working directory is, GetOpenFileName() will preserve it when OFN_NOCHANGEDIR is specified.
Try this:
case ID_PLAY_FFC:
{
FileOpen(hWnd);
}
break;
void FileOpen(HWND hwnd)
{
OPENFILENAME ofn; // common dialog box structure
TCHAR szFile[MAX_PATH+1]; // buffer for file name MAX_PATH = 260
// Zero out szFile so that GetOpenFileName does
// not use the contents to initialize itself.
ZeroMemory(szFile, sizeof(szFile));
// Initialize OPENFILENAME
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hwnd;
ofn.lpstrFile = szFile;
ofn.nMaxFile = MAX_PATH;
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 | OFN_NOCHANGEDIR;
// Display the Open dialog box.
if (GetOpenFileName(&ofn)==TRUE)
{
int ret = (int) ShellExecute(
hwnd,
NULL,
ofn.lpstrFile,
NULL,
TEXT("c:/windows/system32/"),
SW_SHOWNORMAL);
if (ret <= 32)
{
MessageBox(NULL, TEXT("Could not open this file"), TEXT("File I/O Error"), MB_ICONSTOP);
return;
}
}
}