Check if file exists in C++

forivin picture forivin · Jun 9, 2013 · Viewed 22.1k times · Source

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?

Answer

Mats Petersson picture Mats Petersson · Jun 9, 2013

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);
}