Windows check directory exist

How can I check if a directory exists?

How can I check if a directory exists on Linux in C?

6 Answers 6

You can use opendir() and check if ENOENT == errno on failure:

Use the following code to check if a folder exists. It works on both Windows & Linux platforms.

You might use stat() and pass it the address of a struct stat , then check its member st_mode for having S_IFDIR set.

The best way is probably trying to open it, using just opendir() for instance.

Note that it’s always best to try to use a filesystem resource, and handling any errors occuring because it doesn’t exist, rather than just checking and then later trying. There is an obvious race condition in the latter approach.

According to man(2)stat you can use the S_ISDIR macro on the st_mode field:

Side note, I would recommend using Boost and/or Qt4 to make cross-platform support easier if your software can be viable on other OSs.

You may also use access in combination with opendir to determine if the directory exists, and, if the name exists, but is not a directory. For example:

How to check if directory exists in %PATH%?

How does one check if a directory is already present in the PATH environment variable? Here’s a start. All I’ve managed to do with the code below, though, is echo the first directory in %PATH%. Since this is a FOR loop you’d think it would enumerate all the directories in %PATH%, but it only gets the first one.

Is there a better way of doing this? Something like find or findstr operating on the %PATH% variable? I’d just like to check if a directory exists in the list of directories in %PATH%, to avoid adding something that might already be there.

22 Answers 22

First I will point out a number of issues that make this problem difficult to solve perfectly. Then I will present the most bullet-proof solution I have been able to come up with.

For this discussion I will use lower case path to represent a single folder path in the file system, and upper case PATH to represent the PATH environment variable.

From a practical standpoint, most people want to know if PATH contains the logical equivalent of a given path, not whether PATH contains an exact string match of a given path. This can be problematic because:

The trailing \ is optional in a path
Most paths work equally well both with and without the trailing \ . The path logically points to the same location either way. The PATH frequently has a mixture of paths both with and without the trailing \ . This is probably the most common practical issue when searching a PATH for a match.

    There is one exception: The relative path C: (meaning the current working directory of drive C) is very different than C:\ (meaning the root directory of drive C)

Some paths have alternate short names
Any path that does not meet the old 8.3 standard has an alternate short form that does meet the standard. This is another PATH issue that I have seen with some frequency, particularly in business settings.

Windows accepts both / and \ as folder separators within a path.
This is not seen very often, but a path can be specified using / instead of \ and it will function just fine within PATH (as well as in many other Windows contexts)

Windows treats consecutive folder separators as one logical separator.
C:\FOLDER\\ and C:\FOLDER\ are equivalent. This actually helps in many contexts when dealing with a path because a developer can generally append \ to a path without bothering to check if the trailing \ already exists. But this obviously can cause problems if trying to perform an exact string match.

    Exceptions: Not only is C: , different than C:\ , but C:\ (a valid path), is different than C:\\ (an invalid path).

Windows trims trailing dots and spaces from file and directory names.
«C:\test. » is equivalent to «C:\test» .

The current .\ and parent ..\ folder specifiers may appear within a path
Unlikely to be seen in real life, but something like C:\.\parent\child\..\.\child\ is equivalent to C:\parent\child

Читайте также:  Windows installation drivers missing

A path can optionally be enclosed within double quotes.
A path is often enclosed in quotes to protect against special characters like , ; ^ & = . Actually any number of quotes can appear before, within, and/or after the path. They are ignored by Windows except for the purpose of protecting against special characters. The quotes are never required within PATH unless a path contains a ; , but the quotes may be present never-the-less.

A path may be fully qualified or relative.
A fully qualified path points to exactly one specific location within the file system. A relative path location changes depending on the value of current working volumes and directories. There are three primary flavors of relative paths:

  • D: is relative to the current working directory of volume D:
  • \myPath is relative to the current working volume (could be C:, D: etc.)
  • myPath is relative to the current working volume and directory

It is perfectly legal to include a relative path within PATH. This is very common in the Unix world because Unix does not search the current directory by default, so a Unix PATH will often contain .\ . But Windows does search the current directory by default, so relative paths are rare in a Windows PATH.

So in order to reliably check if PATH already contains a path, we need a way to convert any given path into a canonical (standard) form. The

s modifier used by FOR variable and argument expansion is a simple method that addresses issues 1 — 6, and partially addresses issue 7. The

s modifier removes enclosing quotes, but preserves internal quotes. Issue 7 can be fully resolved by explicitly removing quotes from all paths prior to comparison. Note that if a path does not physically exist then the

s modifier will not append the \ to the path, nor will it convert the path into a valid 8.3 format.

The problem with

s is it converts relative paths into fully qualified paths. This is problematic for Issue 8 because a relative path should never match a fully qualified path. We can use FINDSTR regular expressions to classify a path as either fully qualified or relative. A normal fully qualified path must start with : but not : , where is either \ or / . UNC paths are always fully qualified and must start with \\ . When comparing fully qualified paths we use the

s modifier. When comparing relative paths we use the raw strings. Finally, we never compare a fully qualified path to a relative path. This strategy provides a good practical solution for Issue 8. The only limitation is two logically equivalent relative paths could be treated as not matching, but this is a minor concern because relative paths are rare in a Windows PATH.

There are some additional issues that complicate this problem:

9) Normal expansion is not reliable when dealing with a PATH that contains special characters.
Special characters do not need to be quoted within PATH, but they could be. So a PATH like C:\THIS & THAT;»C:\& THE OTHER THING» is perfectly valid, but it cannot be expanded safely using simple expansion because both «%PATH%» and %PATH% will fail.

10) The path delimiter is also valid within a path name
A ; is used to delimit paths within PATH, but ; can also be a valid character within a path, in which case the path must be quoted. This causes a parsing issue.

So we can combine the

s modifier and path classification techniques along with my variation of jeb’s PATH parser to get this nearly bullet proof solution for checking if a given path already exists within PATH. The function can be included and called from within a batch file, or it can stand alone and be called as its own inPath.bat batch file. It looks like a lot of code, but over half of it is comments.

The function can be used like so (assuming the batch file is named inPath.bat):

Typically the reason for checking if a path exists within PATH is because you want to append the path if it isn’t there. This is normally done simply by using something like path %path%;%newPath% . But Issue 9 demonstrates how this is not reliable.

Another issue is how to return the final PATH value across the ENDLOCAL barrier at the end of the function, especially if the function could be called with delayed expansion enabled or disabled. Any unescaped ! will corrupt the value if delayed expansion is enabled.

Читайте также:  Firefox jviewer jnlp linux

Check existence of directory and create if doesn’t exist

I often find myself writing R scripts that generate a lot of output. I find it cleaner to put this output into it’s own directory(s). What I’ve written below will check for the existence of a directory and move into it, or create the directory and then move into it. Is there a better way to approach this?

9 Answers 9

Use showWarnings = FALSE :

dir.create() does not crash if the directory already exists, it just prints out a warning. So if you can live with seeing warnings, there is no problem with just doing this:

As of April 16, 2015, with the release of R 3.2.0 there’s a new function called dir.exists() . To use this function and create the directory if it doesn’t exist, you can use:

This will return FALSE if the directory already exists or is uncreatable, and TRUE if it didn’t exist but was succesfully created.

Note that to simply check if the directory exists you can use

In terms of general architecture I would recommend the following structure with regard to directory creation. This will cover most potential issues and any other issues with directory creation will be detected by the dir.create call.

Also be aware that if

/foo doesn’t exist then a call to dir.create(‘

/foo/bar’) will fail unless you specify recursive = TRUE .

Here’s the simple check, and creates the dir if doesn’t exists:

The use of file.exists() to test for the existence of the directory is a problem in the original post. If subDir included the name of an existing file (rather than just a path), file.exists() would return TRUE, but the call to setwd() would fail because you can’t set the working directory to point at a file.

I would recommend the use of file_test(op=»-d», subDir), which will return «TRUE» if subDir is an existing directory, but FALSE if subDir is an existing file or a non-existent file or directory. Similarly, checking for a file can be accomplished with op=»-f».

Additionally, as described in another comment, the working directory is part of the R environment and should be controlled by the user, not a script. Scripts should, ideally, not change the R environment. To address this problem, I might use options() to store a globally available directory where I wanted all of my output.

So, consider the following solution, where someUniqueTag is just a programmer-defined prefix for the option name, which makes it unlikely that an option with the same name already exists. (For instance, if you were developing a package called «filer», you might use filer.mainDir and filer.subDir).

The following code would be used to set options that are available for use later in other scripts (thus avoiding the use of setwd() in a script), and to create the folder if necessary:

Then, in any subsequent script that needed to manipulate a file in subDir, you might use something like:

This solution leaves the working directory under the control of the user.

How to check whether a file or directory exists? [duplicate]

I want to check the existence of file ./conf/app.ini in my Go code, but I can’t find a good way to do that.

I know there is a method of File in Java: public boolean exists() , which returns true if the file or directory exists.

But how can this be done in Go?

6 Answers 6

Edited to add error handling.

You can use this :

More of an FYI, since I looked around for a few minutes thinking my question be a quick search away.

How to check if path represents an existing directory in Go?

This was the most popular answer in my search results, but here and elsewhere the solutions only provide existence check. To check if path represents an existing directory, I found I could easily:

Part of my problem was that I expected path/filepath package to contain the isDir() function.

Simple way to check whether file exists or not:

I use the following function to check my directories for any errors. It’s very similar to previous answers, but I think not nesting if s makes the code more clear. It uses go-homedir to remove

from directory paths and pkg/errors to return nicer error messages, but it would be easy to take them out if you don’t need their functionality.

Also, to repeat @Dave C’s comment, if the reason you’re checking a directory’s existence is to write a file into it, it’s usually better to simply try to open it an deal with errors afterwards:

Читайте также:  Run program from shell windows

There is simple way to check whether your file exists or not:

How to test if a file is a directory in a batch script?

Is there any way to find out if a file is a directory?

I have the file name in a variable. In Perl I can do this:

22 Answers 22

You can do it like so:

However, this only works for directories without spaces in their names. When you add quotes round the variable to handle the spaces it will stop working. To handle directories with spaces, convert the filename to short 8.3 format as follows:

si converts %%i to an 8.3 filename. To see all the other tricks you can perform with FOR variables enter HELP FOR at a command prompt.

(Note — the example given above is in the format to work in a batch file. To get it work on the command line, replace the %% with % in both places.)

1\» echo It’s a directory – MarioVilas Jun 6 ’13 at 14:08

si* ECHO IS FOLDER – Jakob Sternberg Jan 3 ’14 at 4:16

Works with directory names that contains spaces:

Note that the quotes are necessary if the directory contains spaces:

Can also be expressed as:

This is safe to try at home, kids!

1\» echo It’s a directory – MarioVilas Jun 6 ’13 at 14:10

Recently failed with different approaches from the above. Quite sure they worked in the past, maybe related to dfs here. Now using the files attributes and cut first char

f1 . It expands paths like . and .. to real path. – WesternGun Feb 8 at 22:59

Further to my previous offering, I find this also works:

No quotes around %1 are needed because the caller will supply them. This saves one entire keystroke over my answer of a year ago 😉

Here’s a script that uses FOR to build a fully qualified path, and then pushd to test whether the path is a directory. Notice how it works for paths with spaces, as well as network paths.

Sample output with the above saved as «isdir.bat»:

This works perfectly

1 to remove quotes from %1, and add a backslash at end. Then put thw whole into qutes again.

A variation of @batchman61’s approach (checking the Directory attribute).

This time I use an external ‘find’ command.

(Oh, and note the && trick. This is to avoid the long boring IF ERRORLEVEL syntax.)

  • Directories.
  • Directory symbolic links or junctions.
  • Broken directory symbolic links or junctions. (Doesn’t try to resolve links.)
  • Directories which you have no read permission on (e.g. «C:\System Volume Information»)

The NUL technique seems to only work on 8.3 compliant file names.

(In other words, `D:\Documents and Settings` is «bad» and `D:\DOCUME

I think there is some difficulty using the «NUL» tecnique when there are SPACES in the directory name, such as «Documents and Settings.»

I am using Windows XP service pack 2 and launching the cmd prompt from %SystemRoot%\system32\cmd.exe

Here are some examples of what DID NOT work and what DOES WORK for me:

(These are all demonstrations done «live» at an interactive prompt. I figure that you should get things to work there before trying to debug them in a script.)

This DID NOT work:

D:\Documents and Settings>if exist «D:\Documents and Settings\NUL» echo yes

This DID NOT work:

D:\Documents and Settings>if exist D:\Documents and Settings\NUL echo yes

This DOES work (for me):

D:\Documents and Settings>cd ..

D:\>REM get the short 8.3 name for the file

Volume in drive D has no label. Volume Serial Number is 34BE-F9C9

Directory of D:\
09/25/2008 05:09 PM 2008
09/25/2008 05:14 PM 200809

1.25 2008.09.25
09/23/2008 03:44 PM BOOST_

3 boost_repo_working_copy
09/02/2008 02:13 PM 486,128 CHROME

1.EXE ChromeSetup.exe
02/14/2008 12:32 PM cygwin

[[Look right here . ]]
09/25/2008 08:34 AM DOCUME

1 Documents and Settings

09/11/2008 01:57 PM 0 EMPTY_

1.TXT empty_testcopy_file.txt
01/21/2008 06:58 PM NATION

1 National Instruments Downloads
10/12/2007 11:25 AM NVIDIA
05/13/2008 09:42 AM Office10
09/19/2008 11:08 AM PROGRA

1 Program Files
12/02/1999 02:54 PM 24,576 setx.exe
09/15/2008 11:19 AM TEMP
02/14/2008 12:26 PM tmp
01/21/2008 07:05 PM VXIPNP
09/23/2008 12:15 PM WINDOWS
02/21/2008 03:49 PM wx28
02/29/2008 01:47 PM WXWIDG

2 wxWidgets
3 File(s) 510,704 bytes
20 Dir(s) 238,250,901,504 bytes free

D:\>REM now use the \NUL test with the 8.3 name

D:\>if exist d:\docume

This works, but it’s sort of silly, because the dot already implies i am in a directory:

D:\Documents and Settings>if exist .\NUL echo yes

Оцените статью