How do I find the filepath of the current file?

tl;dr Either of these would work:

  1. How can I get the path to the currently-running file?
  2. How can I determine the path to a file relative to the currently running file / my project / something?

I would like to include a file (a Racket program) which is going to be run via Process. As such, I need to know its filepath so that I can give that to the Process object. In any other language I would simply say "give me the filepath of the current file, then adjust that to get to the desired file which is in the same directory" but that doesn't seem to work. I've been digging around online trying to find how to do this and am finally giving up; code that I've found simply returns nil without error message and all other kinds of frustrations.

I have tried a whole lot of variants involving FileManager and Bundle and etc, but my code currently looks like this:


import Foundation

let engine = Process()
let stdout = Pipe()
let stdin = Pipe()
engine.standardOutput = stdout
engine.standardInput = stdin
engine.executableURL = URL(fileURLWithPath: "/Applications/Racket_v8.11.1/bin/racket")
engine.arguments = ["basic.rkt"]
try engine.run()

let outputData = try stdout.fileHandleForReading.readToEnd()
print(  outputData)

The output is:

open-input-file: cannot open module file
  module path: #<path:/Users/dstorrs/Library/Developer/Xcode/DerivedData/hello-world-bfqcjcdgvknrxefmtpulylvpzuru/Build/Products/Debug/basic.rkt>
  path: /Users/dstorrs/Library/Developer/Xcode/DerivedData/hello-world-bfqcjcdgvknrxefmtpulylvpzuru/Build/Products/Debug/basic.rkt
  system error: no such file or directory; rkt_err=3
nil

Bundle.main.executablePath/URL?

1 Like
    let currentFile = #file

There is also #function, #line, and #column which are very helpful for log messages.

It appears that #filePath may be more future proof

P.S. - If anyone knows where all the built in #something literals are documented, I'd love to know. I only know about them through seeing them in existing code and searches really only turned a proposal or two talking about them. (this includes #colorLiteral, #imageLiteral and #fileLiteral too, really. )

Found the link, they are all macros under the hood now:
https://docs.swift.org/swift-book/documentation/the-swift-programming-language/expressions/#Literal-Expression

1 Like

Bundle.main.executablePath/URL?

Brilliant, thank you.

@carlynorama

There is also #function, #line, and #column which are very helpful for log messages.

Oh, great! Straight out of Perl, that helps a lot. Thank you.

1 Like

shout out to perl.

Alas poor cgi, I knew it.