2

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 :)

Cœur
  • 37,241
  • 25
  • 195
  • 267
Lukasz Czerwinski
  • 13,499
  • 10
  • 55
  • 65

3 Answers3

3

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]);
1

In swift:

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

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

Palle
  • 11,511
  • 2
  • 40
  • 61