1

Let's assume that we have a path /path/to/file that is lowercase. Now on the file system the name of the file is /path/to/File.

How to check if file has correctly the same name.

NSFileManager attributesOfItemAtPath:error: 
NSFileManager fileExistAtPath:

all return YES for both cases. Is there a way to get file system represtentation of the path and compare strings or is there any other extended method to check if file exists with case sensitive name.

patmar
  • 221
  • 1
  • 12

2 Answers2

1

HFS is case insensitive if not explicitly configured otherwise (which seems to be discouraged). This means that /path/to/file and /PaTH/tO/fILe are equivalent.

You can however enumerate the files in a directory and find the name of the file using

NSURL* url = [NSURL fileURLWithPath:@"/path/to/file"];
NSArray *files = [[NSFileManager defaultManager]
                  contentsOfDirectoryAtURL:url.URLByDeletingLastPathComponent
                  includingPropertiesForKeys:nil
                  options:0
                  error:nil];
for (NSString* fileName in files) {
    if ([[fileName lowercaseString] isEqualToString:@"file"]) {
        // fileName is the case sensitive name of the file.
    }
}
Palle
  • 11,511
  • 2
  • 40
  • 61
0

You can open the file and and get its "real" name (as stored in the file system) with a F_GETPATH file system control call:

NSString *path = @"/tmp/x/File.txt";

NSFileManager *fm = [NSFileManager defaultManager];
int fd = open([fm fileSystemRepresentationWithPath:path], O_RDONLY);
if (fd != -1) {
    char buffer[MAXPATHLEN];
    if (fcntl(fd, F_GETPATH, buffer) != -1) {
        NSString *realPath = [fm stringWithFileSystemRepresentation:buffer length:strlen(buffer)];
        NSLog(@"real path: %@", realPath);
    }
    close(fd);
}

Swift version:

let path = "/tmp/x/File.txt"
let fm = FileManager.default
let fd = open(fm.fileSystemRepresentation(withPath: path), O_RDONLY)
if fd != -1 {
    var buffer = [CChar](repeating: 0, count: Int(MAXPATHLEN))
    if fcntl(fd, F_GETPATH, &buffer) != -1 {
        let realPath = String(cString: buffer)
        print("real path: ", realPath)
    }
    close(fd)
}
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382