Filepath from NSFileHandle on iOS (Swift or Objective-C)

1.7k Views Asked by At

I got NSFileHandle from a function call and would like to access the file it refers to. How to get it?

I know that the resource might have multiple file paths or no file path at all (file in memory). However, it would be nice to get anything :)

3

There are 3 best solutions below

0
On

You can use F_GETPATH:

NSFileHandle* Handle = [NSFileHandle fileHandleForReadingAtPath:
                            @"/Applications/TextEdit.app/Contents/Info.plist"];
char Path[MAXPATHLEN];
if (Handle && fcntl([Handle fileDescriptor], F_GETPATH, Path) != -1)
    NSLog(@"%@", [NSString stringWithUTF8String:Path]);
0
On

It is possible to find this information if you really want to. The fstat() call will give you the device and inode number of the file, if it has one. You can then search that device for a file with that inode. But this will be slow, and again it might not even exist.

source

0
On

In swift:

var buffer = [CChar](repeating: 0, count: Int(MAXPATHLEN))
_  = fcntl(fileHandle.fileDescriptor, F_GETPATH, &buffer)
let fileName = String(cString: buffer)