After researching the whole week every day (since previous Monday, 2016-05-30), having tested various "solutions" and having built program hundreds of times, I finally managed to write this code which does not throw any errors or warnings and should find .txt file path in main.cpp folder, successfully replace backslashes with forward slashes and open the text file ready to edit.
Before writing part with LPCSTR, an error was throwing out when I have been trying to use string variable path
in ShellExecute()
instead of manually written path:
cannot convert 'std::string {aka std::basic_string<char>}' to 'LPCSTR {aka const char*}' for argument '3' to 'HISTANCE__* ShellExecuteA(HWND, LPCSTR, LPCSTR...
[documentation]
Now it finds path and replaces slashes perfectly, but does not open a .txt file.
Also, I have tested function CreateProcess()
but I have managed to open (with manually written path in code) only .exe files, not .txt. And when I tried to call function with a string variable in it (at first parameter, which should be LPCSTR), I got the same error, then did the same solution (for error) as shown here and CreateProcess()
did not open .exe file (for example, notepad.exe).
I use GNU GCC compiler, computer OS is 32-bit, Windows.
EDIT: Problem resolved (thanks to Andy) by adding .txt
to "Text"
in GetFullPathName()
:
GetFullPathName("Text.txt", 256, szDir, &fileExt);
#include <iostream>
#include <fstream>
#include <string>
#include <windows.h>
#include <shellapi.h>
#include <stdio.h>
#include <cstring>
using namespace std;
string path; //global variable
void FindFilePath()
{
char szDir[256], buffer[256];
char* fileExt;
GetFullPathName("Text", 256, szDir, &fileExt);
snprintf(buffer, 256, "\"%s\"", szDir); //EDIT: quotes aren't necessary
path = buffer;
string find("\\"), insert("/");
int found = path.find(find);
while (found >= 0) {
if (found >= 0)
path.replace(found, find.size(), insert);
found = path.find(find);
}
/*
If path.find(find) didn't find required symbol, for example,
when string ends, it returns -1 and consequently terminates with
an error 'std::length_error'.
EDIT: replacing isn't necessary.
*/
LPCSTR path2;
{
path2 = path.c_str();
ShellExecute(GetDesktopWindow(), "edit", path2, NULL, NULL, SW_SHOW);
cout << "TEST path2:\n" << path2 << endl;
}
}
int main()
{
ofstream REtext("Text.txt");
REtext.close();
//Created (so that program could find path) or
//restarted text file (so that user had an empty file) in main.cpp folder.
FindFilePath();
cout << "\nPath is: " << path;
return 0;
}
The problem is that GetFullPathName()
isn't returning the full path to the file because only the filename is supplied, not the extension. Once the extension is added, then it will return the absolute path to the file and ShellExecute()
will be able to open it.