Get the parent of a file path

From CodeCodex

Implementations[edit]

Erlang[edit]

% Get the parent of a relative filename path
filename:dirname("test/codex.erl").         % "test"
filename:dirname("codex.erl").              % "."

% Get the parents of an absolute filename path
filename:dirname("/usr/src/codex.erl").     % "/usr/src"

Java[edit]

    // Get the parent of a relative filename path
    File file = new File("Ex1.java");
    String parentPath = file.getParent();      // null
    File parentDir = file.getParentFile();     // null
    
    // Get the parents of an absolute filename path
    file = new File("D:\\almanac\\Ex1.java");
    parentPath = file.getParent();             // D:\almanac
    parentDir = file.getParentFile();          // D:\almanac
    
    parentPath = parentDir.getParent();        // D:\
    parentDir = parentDir.getParentFile();     // D:\
    
    parentPath = parentDir.getParent();        // null
    parentDir = parentDir.getParentFile();     // null

Ruby[edit]

Dir.chdir("/work") do
  # Get the parent of a relative filename path
  fname = "backup/tmp.txt"
  p parent = File.dirname(fname)        #=> "backup"
  p parent = File.dirname(parent)       #=> "."
  p parent = File.dirname(parent)       #=> "."
  
  # Get the parents of an absolute filename path
  p expath = File.expand_path(fname)    #=> "C:/work/backup/tmp.txt"
  p parent = File.dirname(expath)       #=> "C:/work/backup"
  p parent = File.dirname(parent)       #=> "C:/work"
  p parent = File.dirname(parent)       #=> "C:/"
  p parent = File.dirname(parent)       #=> "C:/"
end