QA: How can I know what is a full path to my program that is running?

Vassili Philippov (vasja@spbteam.com), September 07, 2001.

Question

Some my files are located in the same folder as the main executable file. Because Pocket PC does not support local file names I need to know a full path to my executable file to find full path to my other files. How can I do it?

Answer

You can use GetModuleFileName function that gives full path to the executable file of the running program. You could also use GetProgramFilePath and GetProgramFolder functions of CSTUtil class that simplify access to program file name and to path of the folder that contains the program.

Source code

Using STUtil library:

AfxMessageBox(_T("Program: ") + CSTUtil::GetProgramFilePath()); AfxMessageBox(_T("Folder: ") + CSTUtil::GetProgramFolder());

Without using STUtil library:

CString strFilePath; CString strFolderPath; //Get program file path TCHAR lpFileName[MAX_PATH+1]; GetModuleFileName(NULL, lpFileName, MAX_PATH); strFilePath = lpFileName; //Get program folder int nLastIndex = strFilePath.ReverseFind('\\'); if (nLastIndex!=-1) { strFolderPath = strFilePath.Left(nLastIndex); } else { strFolderPath = _T("\\"); } AfxMessageBox(_T("Program: ") + strFilePath); AfxMessageBox(_T("Folder: ") + strFolderPath);

Related resources: