forivin
forivin

Reputation: 59

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?

Upvotes: 4

Views: 22550

Answers (2)

chao
chao

Reputation: 2024

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

Upvotes: 6

Mats Petersson
Mats Petersson

Reputation: 129524

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

Upvotes: 9

Related Questions