Thursday, April 5, 2012

Method to find a file in a directory with C++

Sometimes you may want to check whether a particular file is in the system programatically. Following is a C++ method you can use in Windows enviornment to search for a particular file.


BOOL FindFile(TCHAR* fileName)
{
WIN32_FIND_DATA data;
        //Folder to be searched
HANDLE h = FindFirstFile(L"\\Windows\\*.*",&data);
BOOL returnValue = FALSE;
if( h!=INVALID_HANDLE_VALUE ) 
{
do
{
TCHAR*   nPtr = new TCHAR [lstrlen( data.cFileName ) + 1];
for( int i = 0; i < lstrlen( data.cFileName ); i++ )
nPtr[i] = TCHAR( data.cFileName[i] );


nPtr[lstrlen( data.cFileName )] = '\0';
if(_tcscmp(fileName, nPtr)==0)
{
returnValue == TRUE;
break;
}
//cout << nPtr << endl;


} while(FindNextFile(h,&data));



FindClose(h);


return returnValue;
}

You can call this method inside your main application as mentioned below.

FindFile((LPTSTR)(_T("myfile.xxx")));

1 comment:

  1. Thank you for posting. It's great to learn more about website development. Frankly I've kept reading about website development on your blog. I already bookmarked your link in my browser and send an e-mail to my friends also Joomla Developer .

    ReplyDelete