Find parent directory of file

Started by cormullion, July 04, 2006, 10:42:29 AM

Previous topic - Next topic

cormullion

Given a file coming in through the command line:


(set 'f (main-args 2))

How can I find out what the directory of it is so that I can set the current directory to it?


(change-dir ... f)

The only thing I can see to do is to parse the filename, which seems like the non-newLISP way...

Lutz

#1
you could use real-path to get the full path and then isolate the path chopping off the filename from the end:

(join (chop (parse (real-path (main-args 2)) "/")) "/")


Lutz

cormullion

#2
Thanks, Lutz! I was trying things like parse and even stuff like:


(reverse (member "/" (reverse (real-path f) )))

Yours looks more sensible.



I can imagine a more elegant solution one day - like if change-dir accepted a filename and found the containing directory ...

Sammo

#3
Following Lutz's lead, in Windows I can define:

(define (.. f)
  (join (chop (parse (real-path f) "\") 2) "\") )

(define (. f)
  (join (chop (parse (real-path f) "\") 1) "\") )

Then execute:

(change-dir (.. "c:\path1\path2\path3\filename.txt"))

to change the directory focus to c:/path1/path2, or:

(change-dir (. "c:\path1\path2\path3\filename.txt"))

to change the directory focus to c:/path1/path2/path3.



Something along these lines might be the ticket.

cormullion

#4
Hi Sammo - nice to see you round here! I hadn't thought about the Windows backslash. Doesn't Windows now accept forward slashes? (Sorry I rarely use it at the moment.) So a generic function would be harder.



I like the idea of defining '..' and '.' as functions...