Determine if a file path is a file or a directory

From CodeCodex

Implementations[edit]

Erlang[edit]

-include_lib("kernel-2.xx/include/file.hrl").

file_type(Name) ->
    io:format("'~s'", [Name]),
    case file:read_file_info(Name) of
        {ok, FI} ->
            case FI#file_info.type of
                directory -> io:format(" is a directory~n");
                regular   -> io:format(" is a regular file~n");
                true      -> io:format(" is a special file~n")
            end;
        {error, _} ->
            io:format(" is missing~n")
    end.

Java[edit]

    File dir = new File("directoryName");
    
    boolean isDir = dir.isDirectory();
    if (isDir) {
        // dir is a directory
    } else {
        // dir is a file
    }

Perl[edit]

print "it's a directory\n" if -d $path;
print "it's a file\n" if -f $path;
print "it's a symlink\n" if -l $path;
print "it's a pipe\n" if -p $path;
print "it's a socket\n" if -S $path;

Python[edit]

Note: A Path can be more than a directory or a (normal) file!

import os

if os.path.isdir(path):
    print "it's a directory"
elif os.path.isfile(path):
    print "it's a normal file"
else:
    print "it's a special file (socket, FIFO, device file)"

Ruby[edit]

filename = '/work'
type = File.ftype(filename)
case type
when "file"
  puts "#{filename} is a normal file"
when "directory"
  puts "#{filename} is a directory"
else
  puts "#{filename} is a special file (#{type})"
end