Rename file in Cocoa?

前端 未结 5 1293
再見小時候
再見小時候 2021-01-01 11:11

How would I rename a file, keeping the file in the same directory?

I have a string containing a full path to a file, and a string containing a the new filename (and

5条回答
  •  暖寄归人
    2021-01-01 11:55

    It's worth noting that moving a file to itself will fail. I had a method that replaced spaces with underscores and made the file name lowercase and renamed the file to the new name. Files with only one word in the name would fail the rename as the new name would be identical on a case-insensitive file system.

    The way I resolved this was to do a two step rename, first renaming the file to a temporary name and then renaming it to the intended name.

    Some pseudocode explaining this:

    NSString *source = @"/FILE.txt";
    NSString *newName = [[source lastPathComponent] lowercaseString];
    NSString *target = [[oldPath stringByDeletingLastPathComponent] stringByAppendingPathComponent:newName];
    
    [[NSFileManager defaultManager] movePath:source toPath:target error:nil]; // <-- FAILS
    

    The solution:

    NSString *source = @"/FILE.txt";
    NSString *newName = [[source lastPathComponent] lowercaseString];
    
    NSString *temp = [[oldPath stringByDeletingLastPathComponent] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@-temp", newName]];
    NSString *target = [[oldPath stringByDeletingLastPathComponent] stringByAppendingPathComponent:newName];
    
    [[NSFileManager defaultManager] movePath:source toPath:temp error:nil];
    [[NSFileManager defaultManager] movePath:temp toPath:target error:nil];
    

提交回复
热议问题