gpt4 book ai didi

C++:这是在Windows平台上检查文件存在的最佳方法

转载 作者:IT老高 更新时间:2023-10-28 22:23:02 27 4
gpt4 key购买 nike

Possible Duplicate:
How can we check if a file Exists or not using Win32 program?

检查文件是否存在的最佳方法是:

选项1:

GetFileAttributes("C:\\MyFile.txt"); // from winbase.h
if(0xffffffff == GetFileAttributes("C:\\MyFile.txt"))
{
//File not found
}

选项2:

std::string fileName("C:\\MyFile.txt" );
ifstream fin( fileName.c_str() );

if( fin.fail() )
{
//File not found
}

另外,如果您认为选项 1 是更好的方法,您能告诉我如何将 0xffffffff 定义为常量(我不想使用#define)

谢谢

最佳答案

请注意,GetFileAttributes() 可能由于不存在以外的其他原因(例如权限问题)而失败。我会添加一个检查错误代码的健壮性:

GetFileAttributes("C:\\MyFile.txt"); // from winbase.h
if(INVALID_FILE_ATTRIBUTES == GetFileAttributes("C:\\MyFile.txt") && GetLastError()==ERROR_FILE_NOT_FOUND)
{
//File not found
}

关于C++:这是在Windows平台上检查文件存在的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4403986/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com