4

I'm very very new to C++. In my current project I already included

#include <iostream>
#include <Windows.h>
#include <TlHelp32.h>

and I just need to do a quick check in the very beginning of my main() to see if a required dll exists in the directory of my program. So what would be the best way for me to do that?

jww
  • 97,681
  • 90
  • 411
  • 885
forivin
  • 59
  • 1
  • 1
  • 3
  • Do you mean a DLL required by your program that it is linked against? Or one that you plan to dynamically load with LoadLibrary? – Mats Petersson Jun 08 '13 at 23:44
  • [One way](http://msdn.microsoft.com/en-us/library/windows/desktop/bb773584(v=vs.85).aspx). Depending what you want, certain calls will fail if a file isn't found, too. – chris Jun 08 '13 at 23:44
  • I'm going to inject the dll into another process. And I simply want to end my program, if the dll does not exist. I just want a quick check for that before my program does anything else. How would I use PathFileExists? Since the path is not always the same... – forivin Jun 08 '13 at 23:45
  • Try loading the DLL, since you'll have to do that anyway. If it fails to load, the error code will tell you why. – Jonathan Potter Jun 08 '13 at 23:49

2 Answers2

9

So, assuming it's OK to simply check that the file with the right name EXISTS in the same directory:

#include <fstream>

...

void check_if_dll_exists()
{
    std::ifstream dllfile(".\\myname.dll", std::ios::binary);
    if (!dllfile)
    {
         ... DLL doesn't exist... 
    }
}

If you want to know that it's ACTUALLY a real DLL (rather than someone opening a command prompt and doing type NUL: > myname.dll to create an empty file), you can use:

HMODULE dll = LoadLibrary(".\\myname.dll");

if (!dll)
{
   ... dll doesn't exist or isn't a real dll.... 
}
else
{
   FreeLibrary(dll);
}
Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
6

There are plenty ways you can achieve that, but using boost library is always a good way.

#include <boost/filesystem.hpp>
using boost::filesystem;

if (!exists("lib.dll")) {
    std::cout << "dll does not exists." << std::endl;
}
chao
  • 1,893
  • 2
  • 23
  • 27