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

查看:232
本文介绍了你如何检查是否使用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等),并避免涉及装载非解决方案 - 标准库(如 PathFileExists 在Shlwapi.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.

<一个href=\"http://stackoverflow.com/questions/3828835/how-can-we-check-if-a-file-exists-or-not-using-win32-program\">How我们可以检查文件是否存在,或者不使用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天全站免登陆