Search for path of .exe - c++

So I'm looking for a piece of code that allows me to search for the path of the file it's being executed in. For example, I'm doing an autorun program for use in pendrives (example) but I don't know if it'll end up as D:, F:, G: or whatever so the program would search it's own path and open another file based on the path he is found using some 'if' statements.
Here's what I thought:
#include <stdlib.h>
#include <iostream>
using namespace std;
int main () {
// Insert 'search path' code and needed variables here.
if (-ThePath- == "d:\\AutoRun.exe")
{
system ("d:\\MyFolder\\OtherProgram.exe");
}
else if (-ThePath- == "f:\\AutoRun.exe")
{
system ("f:\\MyFolder\\OtherProgram.exe");
}
else if (-ThePath- == "g:\\AutoRun.exe")
{
system ("g:\\MyFolder\\OtherProgram.exe");
}
else
{
cout << "An error ocurred.\n";
cout << "Press enter to exit...\n";
cin.get();
};
return 0;
}
Is there some way this could be done?

GetModuleFileName : documentation here
EDITED - Pedro, the sample code from Microsoft handles a lot of things. To get the file path, all you need is :
TCHAR szPath[MAX_PATH];
if( !GetModuleFileName( NULL, szPath, MAX_PATH ) ) {
// handle error in GetModuleFileName
} else {
// now, szPath contains file path
};

In standard C++ argv[0] contains the name of the executable. For a program invoked in the normal way this will be the path of the executable on Windows.

Related

WinAPI FileExists Function Implemetation

I am coding a simple replacement for std::filesystem::exists() function using Windows API. Surprisingly, it turned out to be pretty hard. I want to keep my code simple, so I am using minimum functions. My function of choice is GetFileAttributesW(). Code is tested with fs::recursive_directory_iterator() function. My function thinks that all files in “C:\Windows\servicing\LCU*” don’t exist (ERROR_PATH_NOT_FOUND). This directory is responsible for storing Windows Update Caches and is famous for having extremely long file names. I couldn’t find anything else about this directory. Example of filenames and my code are included below. Hope this helps!
Edited:
The solution to this problem is to prepend absolute file path with “\\?\” char sequence. It makes Windows handle short files correctly!
C:\Windows\servicing\LCU\Package_for_RollupFix~31bf3856ad364e35~amd64~~19041.2006.1.7\amd64_microsoft-windows-a..g-whatsnew.appxmain_31bf3856ad364e35_10.0.19041.1741_none_ee5d4a8d060d7653\f\new360videossquare44x44logo.targetsize-16_altform-unplated_contrast-black.png
C:\Windows\servicing\LCU\Package_for_RollupFix~31bf3856ad364e35~amd64~~19041.2006.1.7\amd64_microsoft-windows-a..g-whatsnew.appxmain_31bf3856ad364e35_10.0.19041.1741_none_ee5d4a8d060d7653\f\new360videossquare44x44logo.targetsize-16_altform-unplated_contrast-white.png
C:\Windows\servicing\LCU\Package_for_RollupFix~31bf3856ad364e35~amd64~~19041.2006.1.7\amd64_microsoft-windows-a..g-whatsnew.appxmain_31bf3856ad364e35_10.0.19041.1741_none_ee5d4a8d060d7653\f\new360videossquare44x44logo.targetsize-20_altform-unplated_contrast-black.png
C:\Windows\servicing\LCU\Package_for_RollupFix~31bf3856ad364e35~amd64~~19041.2006.1.7\amd64_microsoft-windows-a..g-whatsnew.appxmain_31bf3856ad364e35_10.0.19041.1741_none_ee5d4a8d060d7653\f\new360videossquare44x44logo.targetsize-20_altform-unplated_contrast-white.png
#include <windows.h>
#include <filesystem>
#include <iostream>
#include <string>
using namespace std;
namespace fs = std::filesystem;
int FileExists(wstring file_path) {
/* TODO:
1. Doesn't work with "C:\\Windows\\servicing\\LCU\\*".
2. Improve error system.
*/
DWORD attributes = GetFileAttributesW(file_path.c_str());
// Valid attributes => File exists
if (attributes != INVALID_FILE_ATTRIBUTES) {
return true;
}
DWORD error_code = GetLastError();
wcout << error_code << ' ' << file_path << '\n';
// Path related error => File doesn't exist
if (error_code == ERROR_PATH_NOT_FOUND || error_code == ERROR_INVALID_NAME ||
error_code == ERROR_FILE_NOT_FOUND || error_code == ERROR_BAD_NETPATH)
{
return false;
}
// Other errors are logged before if statement
// File is busy with IO operations, etc.
return error_code;
}
int main() {
for (fs::path path : fs::recursive_directory_iterator("C:\\", fs::directory_options::skip_permission_denied)) {
FileExists(path);
}
return 0;
}
The solution that worked for me is to prepend absolute file path with “\\?\” char sequence. Somehow, it makes Windows handle shortened file paths correctly!
Check out MSDN Article "Maximum File Path Limitation" for more info.

This breakpoint will not be hit

I looked at numerous posts concerning this problem but none of them apply in my case.
I have a C++ class in one file that has 3 methods. I can set a breakpoint in one method. However, I cannot set a breakpoint on any line of code in the other two methods. This class is build as a library with DEBUG set. All optimizations are turned off.
Below is the code for the two problem methods in this class.
Blockquote
#include "pch.h"
#include <stdio.h>
#include <afxwin.h>
#include <cstring>
#include <io.h>
#include <iostream>
#include <string>
#include "Log.h"
CLog::CLog()
{
ptLog = NULL; // this is the file ptr
}
void CLog::Init()
{
int iFD;
DWORD iLength;
int iStat;
HMODULE hMod;
std::string sPath;
std::string sFile;
int i;
hMod = GetModuleHandle(NULL); // handle to this execuatble
std::cout << "Module = " << hMod;
if(hMod)
{
// Use two bytes ASCII (UNICODE) if set by compiler
char acFile[120];
// Full path name of exe file
GetModuleFileName(hMod, acFile, sizeof(acFile));
std::cout << "File Name = " << acFile<<"\n";
// extract file name from full path and append .log
sPath = acFile;
i = sPath.find_last_of("\\/");
sFile = sPath.substr(i + 1);
sFile.copy(acFile, 120);
std::cout << " File Name Trunc = " << sFile;
sFile.append(".log");
iStat = fopen_s(&ptLog, sFile.data(), "a+"); // append log data to file
std::cout << "fopen stat = " << iStat;
if (iStat != 0) // failed to open error log
{
return;
}
iFD = _fileno(ptLog);
iLength = _filelength(iFD);
// Check length. If too large rename and create new file.
if (iLength > MAX_LOG_SIZE)
{
fclose(ptLog);
char acBakFile[80];
strcpy_s(acBakFile, 80, acFile);
strcat_s(acBakFile, ".bak"); // new name of old log file
remove(acBakFile); // remove previous bak file if it exists
rename(acFile, acBakFile);
fopen_s(&ptLog, acFile, "a+"); // Create new log file
}
}// end if (hMod)
}
,,,
ptLog is declared as FILE *
This class is invoked with the following code:
#include <iostream>
#include "..\Log\Log.h"
int main()
{
CLog Logger;
Logger.Init();
Logger.vLog((char *) "Hello \n");
}
Blockquote
This code is also compiled as debug. If a set a breakpoint on "Loggger.Init()"
the debugger will hit the breakpoint. If select 'Step Into' it will not enter
the code in the Init() method. The code does execute since I can see the text on the console. If I put breakpoints anywhere in the Init() method they do not break.
I did the following:
Removed log.lib from the input to the Linker.
Obviously, the Link failed due to unresolved externals.
Put back log.lib and rebuilt.
Turned off the option "Require source files that exactly match the original version"
Debug and breakpoints worked.
Enabled the option.
Retried debug and the breakpoints still worked.
Did a full rebuild and breakpoints worked.
I don't really understand it because I had performed numerous cleans and rebuilds
previously.
I did find another issue. I had '/clr' option on.
This is for Common Language Runtime support for the .lib.
The module linked to it did not have Common Language Runtime on. In this case,
the breakpoints were ignored. When I turned off '/ clr', the breakpoints
functioned properly

Program with SPI_SETDESKWALLPAPER Function Only Changes the Desktop Background to the Color Black when Trying to Change it to an Image using C++

I am trying to change the desktop background/wallpaper to a different image with a .png file. Although when I run the program, the background turns to solid black instead.
I am certain that I typed the file name, "ksa.png", correctly in my code to be the image I want to be on my background. I used an if condition to write out the last error on a file when the error occurred and used an else condition to write out "Success" if no errors occurred; but when I run the program, it writes "Success" to the file. I have thought about using a .jpg file instead, thinking that maybe .png files just don't work. I'll give an update when I tried using that.
#include <windows.h>
#include <fstream>
int main () {
const wchar_t *filenm = L"ksa.png";
std::ofstream log;
if (SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, (void*)filenm, SPIF_UPDATEINIFILE) == FALSE) {
log.open("log.txt");
log << "Error: " << GetLastError();
log.close();
}
else {
log.open("log.txt");
log << "Success";
log.close();
}
return 0;
}
When I run this program, the desktop background is suppose to be set as the image "ksa.png". Instead it's solid black. Any help is appreciated for making this work, thank you.
UPDATE
Okay so I updated the code to where it would run a .jpg file and I'm still getting the same result. Also I moved the line log.open("log.txt") command before the SystemParametersInfo() function like Remy Lebeau suggested and it still writes out "Success" to the file. I'm still having the same problem.
Here is my updated code:
#include <windows.h>
#include <fstream>
int main () {
const wchar_t *filenm = L"3.jpg";
std::ofstream log;
log.open("log.txt");
if (SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, (void*)filenm, SPIF_UPDATEINIFILE) == FALSE) {
log << "Error: " << GetLastError();
log.close();
}
else {
log.open("log.txt");
log << "Success";
log.close();
}
return 0;
}
Emmmm,there is a problem with your picture path. I've tried your code. You can't get pictures under relative paths unless you use absolute paths.
Like Cody Gray♦'s judgment .
const wchar_t *filenm = L"C:\\Users\\strives\\Desktop\\timg.bmp";

Creating folders in My Documents

I'm having trouble creating a directory structure in the Windows My Documents directory. I use
ExpandEnvironmentStrings(L"%USERPROFILE%\\Documents",dir,MAX_PATH);
to get the directory then I create a new Directory in there
CreateDirectoryW(dir,NULL)
then in there I want to create another directory so in essence i want Documents\foo\bar however when I go to the foo directory via the Library on explorer side bar 'bar' isn't found unless I go to C:\users\xxx\Documents\foo then its there. Also if I go to Libraries\Documents\foo and right click->New->Folder isn't an option.
I was wondering if there is a Security Option to CreateDirectory I'm supposed to use or what I'm doing wrong
If you want to create a directory tree, you can use SHCreateDirectoryEx. The following code works well on my computer.
#include <iostream>
#include <Windows.h>
#include <Shlobj.h>
#include <Shlwapi.h>
int main()
{
char path[MAX_PATH];
if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_COMMON_DOCUMENTS, NULL, 0, path)))
{
PathAppend(path, "foo\\bar");
if (SHCreateDirectoryEx(NULL, path, NULL) != ERROR_SUCCESS)
{
std::cout << "Error: " << GetLastError();
}
}
else
{
std::cout << "Error: " << GetLastError();
}
}
Notice that this works only on Windows 2000 Professional or higher.

how to search the computer for files and folders

i need a way to search the computer for files like Windows Explorer. i want my program to search lets say hard drive c:. i need it to search C:\ for folders and files (just the ones you could see in c:\ then if the user clicks on a file on the list like the folder test (C:\test) it would search test and let the user see what files/folders are in it.
Since you mentioned windows, the most straight forward winapi way to do it is with FindFirstFile and FindNextFile functions.
edit: Here's an example that shows you how to enumerate all files/folders in a directory.
#include <Windows.h>
#include <iostream>
int main()
{
WIN32_FIND_DATA file;
HANDLE search_handle=FindFirstFile(L"C:\\*",&file);
if (search_handle)
{
do
{
std::wcout << file.cFileName << std::endl;
}while(FindNextFile(search_handle,&file));
FindClose(search_handle);
}
}
This will be OS dependent. The SO question
How can I get a list of files in a directory using C or C++?
handles this problem well. You can download DIRENT here.
Now that you have this, I'd recommend recursively searching for a file with a DFS/BFS algorithm. You can assume the whole directory structure is a tree where each file is a leaf node and each subdirectory is an internal node.
So all you have to do is,
Get the list of files/folders in a directory with a function such as:
void getFilesFolders(vector<string> & dir_list, const string & folder_name)
If it's a directory, go to 1 with the directory name
If it's a file, terminate if it's the file you're looking for, else move on to the next file.
boost::filesystem can be a cross-platform solution for that (check out for such functions in it).
You can use Directory class members to do this with C# or managed C++. See the following MSDN article:
http://support.microsoft.com/kb/307009
If you wish to use C++ with MFC you can use CFileFind
http://msdn.microsoft.com/en-us/library/f33e1618%28v=VS.80%29.aspx
You'll have to supply your own browse window to present the file system tree.
Or you can use one of the directory/file controls to do both for you.
#include <Windows.h>
#include <iostream>
int FindF(char* pDirectory)
{
char szFindPath[MAX_PATH] = {0};
strcpy(szFindPath, pDirectory);
strcat(szFindPath, "\\*");
WIN32_FIND_DATA file;
HANDLE search_handle=FindFirstFile(szFindPath,&file);
if (search_handle)
{
do
{
if(file.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY)
{
strcpy(szFindPath, pDirectory);
strcat(szFindPath, "\\");
strcat(szFindPath, file.cFileName);
FindF(szFindPath);
}
std::wcout << file.cFileName << std::endl;
}while(FindNextFile(search_handle,&file));
CloseHandle(search_handle);
}
}
There really is no need to use 3rd party library to accomplish this. This is a short, independent function which lists all files (with their paths) in a directory, including subdiretories' files. std::string folderName has to finish with \, and if you want to list all files on computer, just create a loop in calling function along with GetLogicalDriveStrings (It returns strings with \, so it couldn't be more convenient in this case).
void FindAllFiles(std::string folderName)
{
WIN32_FIND_DATA FileData;
std::string folderNameWithSt = folderName + "*";
HANDLE FirstFile = FindFirstFile(folderNameWithSt.c_str(), &FileData);
if (FirstFile != INVALID_HANDLE_VALUE) {
do {
if (strcmp(FileData.cFileName, ".") != 0 && strcmp(FileData.cFileName, "..") != 0)
{
if(FileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
std::string NewPath = folderName + FileData.cFileName;
NewPath = NewPath + "\\";
FindAllFiles(NewPath);
}
else
{
std::cout /*<< folderName*/ << FileData.cFileName << std::endl;
}
}
} while(FindNextFile(FirstFile, &FileData));
}
}
This is ASCII version, remember that files and folders can be named in Unicode