如何在 C 中检查 Windows 上是否存在目录? [英] How do you check if a directory exists on Windows in C?

查看:31
本文介绍了如何在 C 中检查 Windows 上是否存在目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Windows C 应用程序中,我想验证传递给函数的参数以确保指定的路径存在.*

In a Windows C application I want to validate a parameter passed into a function to ensure that the specified path exists.*

如何用 C 语言检查 Windows 上是否存在目录?

*我知道您可能会进入竞争条件,在您检查存在的时间和您使用它不再存在的路径的时间之间,但我可以处理.

*I understand that you can get into race conditions where between the time you check for the existance and the time you use the path that it no longer exists, but I can deal with that.

当权限发挥作用时,明确知道目录存在或不存在可能会变得棘手.有可能在尝试确定目录是否存在时,进程没有访问目录或父目录的权限.这可以满足我的需求.如果目录不存在或我无法访问它,则两者都在我的应用程序中被视为无效路径故障,因此我不需要区分.如果您的解决方案提供了这种区别,则可获得(虚拟)奖励积分.

Knowing explicitly that a directory does or does not exist can get tricky when permissions come into play. It's possible that in attempting to determine if the directory exists, the process doesn't have permissions to access the directory or a parent directory. This is OK for my needs. If the directory doesn't exist OR I can't access it, both are treated as an invalid path failure in my application, so I don't need to differentiate. (Virtual) bonus points if your solution provides for this distinction.

C 语言、C 运行时库或 Win32 API 中的任何解决方案都可以,但理想情况下我想坚持使用通常加载的库(例如 kernel32、user32 等)并避免涉及加载非- 标准库(如 PathFileExistsShlwapi.dll).同样,如果您的解决方案是跨平台的,则(虚拟)奖励积分.

Any solution in the C language, C runtime library, or Win32 API is fine, but ideally I'd like to stick to libraries that are commonly loaded (e.g. kernel32, user32, etc.) and avoid solutions that involve loading non-standard libraries (like PathFileExists in Shlwapi.dll). Again, (Virtual) bonus points if your solution is cross-platform.

我们怎样才能使用Win32程序检查文件是否存在?

推荐答案

做这样的事情:

BOOL DirectoryExists(LPCTSTR szPath)
{
  DWORD dwAttrib = GetFileAttributes(szPath);

  return (dwAttrib != INVALID_FILE_ATTRIBUTES && 
         (dwAttrib & FILE_ATTRIBUTE_DIRECTORY));
}

GetFileAttributes() 方法包含在 Kernel32 中.dll.

The GetFileAttributes() method is included in Kernel32.dll.

这篇关于如何在 C 中检查 Windows 上是否存在目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆