I am still kinda bad in c so pls dont mind my bad code or my missing knowledge. The project is about chosing a file and the paste it in the console for the user to read and i thought the best way would be using a dialog window (and i get more practice using the winapi).
Here my code for the window:
OPENFILENAMEA NameOfFile;
ZeroMemory(&NameOfFile, sizeof(NameOfFile));
NameOfFile.nFileOffset = 1;
char szFile[260];
NameOfFile.lpstrFile[0] = '\0';
NameOfFile.lpstrFile = szFile;
NameOfFile.nMaxFile = 4096;
NameOfFile.Flags = OFN_ALLOWMULTISELECT;
if (GetOpenFileName(&NameOfFile)) {
cout << "opened";
}
Now the wierd thing. The Programm crashes with the error "-1073741819". Google said its an access violation of smth (no clue what exactly it means).
When i comment out the ZeroMemory function i got a linker and compiler error that NameOfFile is apparently not initialized??? (but if its not commented it compiles normally?!)
CodePudding user response:
There are several issues in your code:
- You need to set the
lStructSize
field of yourOPENFILENAMEA
variable. - You need to swap the 2 lines setting
NameOfFile.lpstrFile
, so that the pointer that you access (in order to write the zero termination) will point to a valid buffer. NameOfFile.nMaxFile
should be set to the size of the filename pointer bylpstrFile
, i.e. thesizeof(szFile)
.
Fixed version:
OPENFILENAMEA NameOfFile;
ZeroMemory(&NameOfFile, sizeof(NameOfFile));
NameOfFile.lStructSize = sizeof(NameOfFile); // Item 1 above
char szFile[260];
NameOfFile.lpstrFile = szFile; // Item 2 above
NameOfFile.lpstrFile[0] = '\0'; // Item 2 above
NameOfFile.nMaxFile = sizeof(szFile); // Item 3 above
NameOfFile.Flags = OFN_ALLOWMULTISELECT;
if (GetOpenFileName(&NameOfFile))
{
std::cout << "opened";
}
For additional info you can see the example in the MS documentation here under the "Opening a File" section.
A side note: better to avoid using namespace std
- see here Why is "using namespace std;" considered bad practice?.