Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if file exists in C++

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?

like image 389
forivin Avatar asked Dec 06 '22 07:12

forivin


1 Answers

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);
}
like image 85
Mats Petersson Avatar answered Dec 13 '22 20:12

Mats Petersson