I have a file path as a string. I want to:
the problem I'm having is that sometimes that file path involves a symbolic link (symlink). Maybe to the file itself. Maybe to one of the directories above the file.
[EDIT] closing this because the following code (that I started with), actually works just fine, there were just multiple levels of user error involved. Thanks for the input folks.
func getUserResource(relativeFilePath: String) -> String? {
let fileManager = NSFileManager.defaultManager()
let userFilePath = NSHomeDirectory() + relativeFilePath
if(fileManager.fileExistsAtPath(userFilePath))
{
do {
return try String(contentsOfFile: userFilePath, encoding: NSUTF8StringEncoding);
} catch {
return nil;
}
}
return nil;
}
If you're not sure if the symlink leads to a file or directory, you should be using fileExistsAtPath(path:, isDirectory:)
. fileExistsAtPath
will always return true
for a symlink, because technically there is a file at that path. By passing a boolean pointer to isDirectory
, you can follow the symlink to a file or to a directory:
Assume symlinkToSomeFile
is a symbolic link to a file and symlinkToSomeDir
is a symbolic link to a directory.
let symlinkFilePath = NSHomeDirectory() + "/temp/symlinkToSomeFile"
let symlinkDirPath = NSHomeDirectory() + "/temp/symlinkToSomeDir"
var fileCheck: ObjCBool = false
var dirCheck: ObjCBool = false
print(fileManager.fileExistsAtPath(symlinkFilePath, isDirectory: &fileCheck)) // true
print(fileCheck) // false
print(fileManager.fileExistsAtPath(symlinkDirPath, isDirectory: &dirCheck)) // true
print(dirCheck) // true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With