'Fstream Couldn't Open File
After saving file with widows.h save dialog and fstream in other directory I couldn`t open file in program directory.
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hMainWindow;
ofn.lpstrFilter = L"Text Files (*.txt)\0*.txt\0Word Files (*.rtf)\0*.rtf\0";
ofn.lpstrFile = FileName;
ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = MAX_NAME_STRING;
ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
ofn.lpstrDefExt = L"txt";
ofn.nFilterIndex = 1;
if (GetSaveFileName(&ofn) == TRUE) {
std::fstream file;
file.open(FileName, std::ios::out);
//Write To File
file.clear();
file.close();
}
std::fstream code;
code.open("CodeTemplate.template", std::ios::in);
//ERROR: File Couldn't Open, But File Exists in Program Directory
code.clear();
code.close();
If I Copy That File "CodeTemplate.template" To directroy that have been selected in save dialog file opens.
Solution 1:[1]
GetSaveFileName() returns an absolute path to the selected file. So you are passing an absolute path to the output fstream to create the file.
But, you are passing a relative path to the input fstream to open the file. Since that is failing, it is likely that the calling process' current working directory is not pointing where you are expecting.
You even said yourself that you have to "Copy [CodeTemplate.template] To directroy that have been selected in save dialog" to make the file open correctly. Which means that file does not exist in the folder where the working directory is pointing at.
In short, you should never rely on relative paths when creating/opening files. The working directory is volatile, it can change dynamically, and so it may not always point where you are expecting. Always use absolute paths.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
