Find parent directory of file

Q&A's, tips, howto's
Locked
cormullion
Posts: 2038
Joined: Tue Nov 29, 2005 8:28 pm
Location: latiitude 50N longitude 3W
Contact:

Find parent directory of file

Post by cormullion »

Given a file coming in through the command line:

Code: Select all

(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?

Code: Select all

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

Lutz
Posts: 5289
Joined: Thu Sep 26, 2002 4:45 pm
Location: Pasadena, California
Contact:

Post by Lutz »

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

Code: Select all

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

cormullion
Posts: 2038
Joined: Tue Nov 29, 2005 8:28 pm
Location: latiitude 50N longitude 3W
Contact:

Post by cormullion »

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

Code: Select all

(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
Posts: 180
Joined: Sat Dec 06, 2003 6:11 pm
Location: Loveland, Colorado USA

Post by Sammo »

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

Code: Select all

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

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

Code: Select all

(change-dir (.. "c:\\path1\\path2\\path3\\filename.txt"))
to change the directory focus to c:/path1/path2, or:

Code: Select all

(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
Posts: 2038
Joined: Tue Nov 29, 2005 8:28 pm
Location: latiitude 50N longitude 3W
Contact:

Post by cormullion »

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...

Locked