【问题标题】:Checking case sensitive file name HFS检查区分大小写的文件名 HFS
【发布时间】:2017-08-25 09:17:05
【问题描述】:

假设我们有一个小写的路径 /path/to/file。 现在在文件系统上,文件的名称是 /path/to/File。

如何检查文件是否具有正确的相同名称。

NSFileManager attributesOfItemAtPath:error: 
NSFileManager fileExistAtPath:

这两种情况都返回 YES。有没有办法获取路径的文件系统表示并比较字符串,或者是否有任何其他扩展方法来检查文件是否存在区分大小写的名称。

【问题讨论】:

    标签: objective-c macos hfs


    【解决方案1】:

    如果没有明确配置,HFS 不区分大小写(这似乎不鼓励)。这意味着/path/to/file/PaTH/tO/fILe 是等价的。

    但是,您可以枚举目录中的文件并使用查找文件的名称

    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.
        }
    }
    

    【讨论】:

      【解决方案2】:

      您可以打开文件并获取其“真实”名称(存储在 文件系统)与F_GETPATH 文件系统控制调用:

      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 版本:

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

      【讨论】:

        猜你喜欢
        • 2012-11-17
        • 1970-01-01
        • 2012-02-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-16
        • 2021-12-03
        • 1970-01-01
        相关资源
        最近更新 更多