Reputation: 401
I have this C code that retrieves the path of the executable.
char buffer[300];
char *appPath;
GetModuleFileName(NULL,buffer,300);
appPath = buffer;
MessageBox(NULL,appPath,"path",MB_OK);
That code returns a messagebox contains e.g
C:\myexe.exe
i'm trying to make it return :
"C:\myexe.exe"
Already found and tried solutions on those posts 1 and 2 but they are not compatible with my problem.
Any hint ?
Upvotes: 0
Views: 2251
Reputation: 7320
You could simply do it like this :
char buffer[302]; //< I assume you picked 300 for a reason, so 302 for the extra quotes
char *appPath;
int fileNameLen = GetModuleFileName(NULL,buffer+1,300);
buffer[0] = buffer[fileNameLen+1] = '"'; //< Wrap in quotes
buffer[fileNameLen+2] = '\0'; //< Now add the \0 back
appPath = buffer;
MessageBox(NULL,appPath,"path",MB_OK);
Note that there's still no error checking here in case GetModuleFileName
fails, you might want to add some.
This code should run faster than calling some libc string functions, but it may not be the best choice if you find it harder to read.
Upvotes: 2
Reputation: 182609
How about creating a new string with snprintf
?
char somestr[..];
snprintf(somestr, sizeof somestr, "\"%s\"", appPath);
Upvotes: 7