Click to See Complete Forum and Search --> : Folder Locations
MrDoomMaster
April 22nd, 2005, 03:49 AM
I need a way to know what folder my program is in at the current time of execution. Basically, my program is a single EXE file that needs to be able to add and edit files (specifically INI files) to the current directory to which it is located.
Andreas Masur
April 22nd, 2005, 04:32 AM
How to get the current working directory? (http://www.codeguru.com/forum/showthread.php?t=312470)
How to get the application directory? (http://www.codeguru.com/forum/showthread.php?t=312471)
The former one will give you the current working directory which might change during run-time...the latter one will give you the directory of your application...
Bond
April 22nd, 2005, 08:41 AM
I use a function like this in many of my programs to easily create a path to a file with the same name as my EXE, but with a different extension (INI, LOG, CSV, TXT, etc.).
BOOL GetApplicationFile(LPCTSTR pszExt, LPTSTR pszPath, int iMaxLength)
{
GetModuleFileName(NULL, pszPath, iMaxLength);
lstrcpyn(_tcsrchr(pszPath, '.') + 1, pszExt, iMaxLength);
return FileExists(pszPath);
}
(In this case, I've combined it with another function, FileExists(), to inform me if the file has already been created).
Call the function like so:
TCHAR szIniFile[MAX_PATH];
if (GetApplicationFile(TEXT("ini"), szIniFile, sizeof(szIniFile) / sizeof(TCHAR))
{
// File already exists. Open the file (szIniFile) and use it...
}
else
{
// File doesn't exist. Create the file (szIniFile) and use it...
}
I'm obviously skipping some error checking but GetModuleFileName() has never failed me. You may not want to be so trusting.
MrDoomMaster
April 23rd, 2005, 01:05 PM
Thanks a bunch guys for your replies. I gave up checking the FAQ's on the forum when I found out they don't normally answer most of my questions. I guess they did help with this one though :)
I'll give you both some rep points, if I'm allowed.
Oliver M.
April 23rd, 2005, 04:26 PM
Two notes about GetModuleFileName:
1) If the first parameter is NULL, it always returns the filename of the calling process. This might be important if you call it from a DLL and need the name of the DLL.
2) Well, if you need to keep compatibility with outdated OS, MSDN says: "Windows 95: The GetModuleFilename function will return long filenames when an application's version number is greater than or equal to 4.00 and the long filename is available. Otherwise, it returns only 8.3 format filenames."
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.