C++:哪个是在 Windows 平台上检查文件存在的最佳方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4403986/
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
C++: Which is the best method of checking for file existence on windows platform
提问by Robben_Ford_Fan_boy
Possible Duplicate:
How can we check if a file Exists or not using Win32 program?
可能的重复:
我们如何使用 Win32 程序检查文件是否存在?
Which is the best method for checking for file existence:
哪个是检查文件存在的最佳方法:
Option1:
选项1:
GetFileAttributes("C:\MyFile.txt"); // from winbase.h
if(0xffffffff == GetFileAttributes("C:\MyFile.txt"))
{
//File not found
}
Option2:
选项2:
std::string fileName("C:\MyFile.txt" );
ifstream fin( fileName.c_str() );
if( fin.fail() )
{
//File not found
}
Also if you think option 1 is the better method, can you tell me how to define 0xffffffff
as a constant (I don't want to use #define)
另外,如果您认为选项 1 是更好的方法,您能告诉我如何定义0xffffffff
为常量吗(我不想使用 #define)
Thanks
谢谢
回答by zdan
Note that GetFileAttributes() may fail for other reasons than lack of existence (for example permissions issues). I would add a check on the error code for robustness:
请注意,GetFileAttributes() 可能会因其他原因而失败,而不是不存在(例如权限问题)。我会添加对错误代码的稳健性检查:
GetFileAttributes("C:\MyFile.txt"); // from winbase.h
if(INVALID_FILE_ATTRIBUTES == GetFileAttributes("C:\MyFile.txt") && GetLastError()==ERROR_FILE_NOT_FOUND)
{
//File not found
}
回答by Chris Becke
There are two things to consider here:
这里有两件事需要考虑:
Checking if the file exists via its attributes is potentially many orders of magnitude faster - If a file exists on a 'slow' file system - tape, network storage, cd etc then opening the file will involve an actual round trip to the files location. The files attributes on the other hand are queried and cached by the filesystem drivers when the directory is queried, so probing file attributes involves a once off directory enumeration cost - meaning far fewer round trips - which can be a significant saving if multiple "slow" files are being checked.
However, the files attributes merely indicate that the file existed at the time the call was made. The file can be deleted, or you might not haver permissions to access it. If you are about to try and open the file anyway, it would be better to dispense with the file attributes check and actually try and open the file.
通过其属性检查文件是否存在可能要快许多数量级 - 如果文件存在于“慢”文件系统 - 磁带、网络存储、CD 等,则打开文件将涉及到文件位置的实际往返。另一方面,文件属性在查询目录时由文件系统驱动程序查询和缓存,因此探测文件属性涉及一次性目录枚举成本 - 这意味着往返次数要少得多 - 如果多个“慢”,这可以显着节省正在检查文件。
但是,文件属性仅表明该文件在进行调用时存在。该文件可以被删除,或者您可能没有访问它的权限。如果您无论如何都要尝试打开文件,最好省去文件属性检查并实际尝试打开文件。
回答by Inverse
How about use boost?
使用boost怎么样?
if (!boost::filesystem::exists("C:\MyFile.txt"))
{
...
}
http://www.boost.org/doc/libs/1_43_0/libs/filesystem/doc/index.htm
http://www.boost.org/doc/libs/1_43_0/libs/filesystem/doc/index.htm
回答by casablanca
If you're targeting only Windows, option #1 is clearly the better of the two. Also, the constant you're looking for already exists in the Windows headers -- it's called INVALID_FILE_ATTRIBUTES
.
如果您只针对 Windows,那么选项 #1 显然是两者中更好的一个。此外,您要查找的常量已经存在于 Windows 标头中——它被称为INVALID_FILE_ATTRIBUTES
.
回答by jalf
The onlyrobust way to check whether a file exists is to try to open it, and see if it succeeds or fails.
检查文件是否存在的唯一可靠方法是尝试打开它,看看它是成功还是失败。
Anyother method is a potential race condition. For example, GetFileAttributes
can tell you if a file existed when you called the function, but that's not the same as whether it exists when you try to open it. It might have been deleted (or created) in the meantime.
任何其他方法都是潜在的竞争条件。例如,GetFileAttributes
可以在您调用函数时告诉您文件是否存在,但这与您尝试打开它时是否存在不同。在此期间它可能已被删除(或创建)。
回答by GolezTrol
I would prefer the first. The second checks if the file can be opened, while a file might exist without you having the rights to open it.
我更喜欢第一个。第二个检查文件是否可以打开,而文件可能存在而您没有打开它的权限。
You can use the INVALID_FILE_ATTRIBUTES
constant.
您可以使用INVALID_FILE_ATTRIBUTES
常量。
回答by Courtney Christensen
I'd opt to use the iostream
because of its platform independence. True, you may be targeting Windows only, but it's never a bad move to use platform-independent libraries. If you're building a big project, you never know what that next phase will entail.
我会选择使用 ,iostream
因为它的平台独立性。诚然,您可能只针对 Windows,但使用独立于平台的库绝非坏事。如果您正在构建一个大项目,您永远不知道下一阶段会带来什么。
I'm not sure the code above is the best (or correct) way to check for file existence. Try this:
我不确定上面的代码是检查文件存在的最佳(或正确)方法。试试这个:
ifstream f;
f.open(str);
if (f.is_open()) {
// read file
}
回答by sean e
I also like to confirm that the string isn't a directory:
我还想确认该字符串不是目录:
DWORD attr = GetFileAttributes(file);
if(attr == INVALID_FILE_ATTRIBUTES || (attr & FILE_ATTRIBUTE_DIRECTORY))
return false; // not a file
return true;
回答by weloytty
Back in the day, all we had was OpenFile (and we were GRATEFUL)
回到那天,我们只有 OpenFile(我们很感激)
OFSTRUCT of = {0};
of.cBytes = sizeof(of);
HFILE hf = ::OpenFile("c:\windows\write.exe",&of,OF_EXIST);
if(hf > 0)
printf("file exists");
return 0;
回答by Ofek Shilon
There's a nice shell utility function for that, PathFileExists.
有一个很好的 shell 实用程序函数,PathFileExists。