Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you check if a directory exists on Windows in C?

Tags:

c

windows

winapi

Question

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

How do you check if a directory exists on Windows in C?

*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.

Additional Background

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.

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.

Related

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

like image 468
Zach Burlingame Avatar asked Jun 02 '11 17:06

Zach Burlingame


People also ask

How do you check if it is a file or directory in C?

The isDir() function is used to check a given file is a directory or not.

How do I check if a directory exists in C ++?

Call DirectoryExists() to determine whether the directory specified by the Directory parameter exists. If the directory exists, the function returns True. If the directory does not exist, the function returns False.


1 Answers

Do something like this:

BOOL DirectoryExists(LPCTSTR szPath) {   DWORD dwAttrib = GetFileAttributes(szPath);    return (dwAttrib != INVALID_FILE_ATTRIBUTES &&           (dwAttrib & FILE_ATTRIBUTE_DIRECTORY)); } 

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

like image 102
retrodrone Avatar answered Sep 19 '22 15:09

retrodrone