Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle symlinks when reading data from a file path in swift

I have a file path as a string. I want to:

  1. Test if there's a file there
  2. Read the contents of the file as a string

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;
}
like image 359
masukomi Avatar asked Jun 01 '16 12:06

masukomi


1 Answers

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
like image 54
JAL Avatar answered Oct 17 '22 03:10

JAL