检查文件是否存在于 C++
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17005006/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if file exists in C++
提问by forivin
I'm very very new to C++. In my current project I already included
我对 C++ 非常陌生。在我目前的项目中,我已经包括
#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?
我只需要在 main() 的最开始快速检查一下我的程序目录中是否存在所需的 dll。那么对我来说最好的方法是什么?
回答by Mats Petersson
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:
如果您想知道它实际上是一个真正的 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);
}
回答by chao
There are plenty ways you can achieve that, but using boost library is always a good way.
有很多方法可以实现这一点,但使用 boost 库总是一个好方法。
#include <boost/filesystem.hpp>
using boost::filesystem;
if (!exists("lib.dll")) {
std::cout << "dll does not exists." << std::endl;
}