Posts tagged FindFirstFile()
How to check whether a file exists of not?
2![]()
While reading configuration file, while reading some setting file, every where we’ve to check whether the file exists or not before opening and starts reading. The simple technique is to open the file by using file apis or to search for the file by using FindFirstFile(). Or is there any simple api to do so?
![]()
You can use the api – PathFileExists(). Check the following code snippet.
#include "shlwapi.h"
...
// File path.
CString csFile = _T( "C:\\Autumn Leaves.jpg");
if( PathFileExists( csFile ))
{
// Yes! the file exists.
}
![]()
Don’t forget to add shlwapi.lib to your project settings.
![]()
Targeted Audience – Beginners.
How to list directories / files of a given path in your listbox easily?
4![]()
Assume you’ve a listbox and you want to fill all directories/files of a particular path to it. The usual method is iterate each file by FindFirstFile() and FindNextFile(), then add to listbox. Or any other cool tricks to do the same more easily?
![]()
You can use the api – DlgDirList(). It will populate the directories or files or drives to your listbox. You can select it by providing appropriate options. See the sample code snippet below, which lists all directories under C:\.
// The path Variable should be modifiable buffer. // Since DlgDirList() returns data through it. TCHAR Path[MAX_PATH] = _T("C:\\"); ::DlgDirList( GetSafeHwnd(), Path, // in/out param. IDC_LIST1, 0, DDL_DIRECTORY | DDL_EXCLUSIVE );
For identifying directories, the DlgDirList() will decorate the directory name in format “[Directory]“. Now how to get the selected directory path from the listbox? Since its decorated, for that purpose, you can use function – DlgDirSelectEx(). It will undecorated the directory name and returns the real name. See the code snippet below.
// Read the selected directory from Listbox
TCHAR SelectedPath[MAX_PATH] = { 0 };
DlgDirSelectEx( GetSafeHwnd(),
SelectedPath,
MAX_PATH,
IDC_LIST1 );
![]()
Have a look at similar apis, such as DlgDirListComboBox(), DlgDirListComboBoxEx() etc. The name itself explains about it. Isn’t it?
![]()
Targeted Audience – Intermediate.