Check if file exists in C++

牧云@^-^@ 提交于 2019-12-01 21:13:42

问题


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?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/17005006/check-if-file-exists-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!