检查c++中是否存在file

Check if file exists in C++

本文关键字:存在 file 是否 c++ 检查      更新时间:2023-10-16

我对c++非常非常陌生。在我当前的项目中,我已经包含了

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

,我只需要在main()的开头做一个快速检查,看看我的程序目录中是否存在所需的dll。那么对我来说什么是最好的方法呢?

那么,假设可以简单地检查具有正确名称的文件是否存在于同一目录中:

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

如果你想知道它实际上是一个真正的DLL(而不是某人打开命令提示符并执行type NUL: > myname.dll来创建一个空文件),你可以使用:

HMODULE dll = LoadLibrary(".\myname.dll");
if (!dll)
{
   ... dll doesn't exist or isn't a real dll.... 
}
else
{
   FreeLibrary(dll);
}

有很多方法可以实现这一点,但使用boost库始终是一种好方法。

#include <boost/filesystem.hpp>
using boost::filesystem;
if (!exists("lib.dll")) {
    std::cout << "dll does not exists." << std::endl;
}