You are here

상대패스로 변경하기

Tcl의 기본 커맨드중 절대패스로 변경하는 file normalize 커맨드가 있습니다.

이 커맨드를 사용하여 상대패스로 변경합니다.

 proc relpath {basedir target} {
     # Try and make a relative path to a target file/dir from base directory

     set bparts [file split [file normalize $basedir]]
     set tparts [file split [file normalize $target]]

     if {[lindex $bparts 0] eq [lindex $tparts 0]} {
        # If the first part doesn't match - there is no good relative path

        set blen [llength $bparts]
        set tlen [llength $tparts]
        for {set i 1} {$i < $blen && $i < $tlen} {incr i} {
            if {[lindex $bparts $i] ne [lindex $tparts $i]} { break }
        set path [lrange $tparts $i end]
        for {} {$i < $blen} {incr i} {
            set path [linsert $path 0 ..]
        return [eval [list file join] $path]

     return $target

 # Some examples

 relpath C:/Tcl/lib/tcllib C:/Tcl/lib/tcllib/module/pkgIndex.tcl
# module/pkgIndex.tcl
 relpath [file dirname [info nameofexe]] [info library]
# ../lib/tcl8.4
 relpath C:/Tcl/foo D:/Tcl/bar
# D:/Tcl/bar
 relpath /usr/bin /usr/local/bin/tclsh
# ../local/bin/tclsh