如果已存在,如何将副本添加到文件名?

时间:2015-12-06 15:32:28

标签: objective-c macos cocoa

如果文件已经存在(例如/hello.txt)并运行命令,是否有办法:

[data writeToFile:@"/hello.txt" atomically:YES];

而不是覆盖创建文件hello copy.txt然后hello copy 2.txt,因为finder自然会这样做吗?

1 个答案:

答案 0 :(得分:2)

首先,您需要使用拒绝覆盖现有文件的数据写入方法。您可以将-[NSData writeToFile:options:error:]NSDataWritingWithoutOverwriting选项一起使用。检查其返回值以查看它是否失败,然后检查返回的NSError以查看它失败的原因是否是现有文件。如果是,则根据您创建的原始和尝试次数构建新的路径字符串,添加"拷贝"或"复制%u",然后循环再试一次。如果成功或者出现任何其他错误,请停止循环。 (如果发生无法预料的情况,您也可以对最大尝试次数设置限制。)

NSError表示失败,因为如果domainNSCocoaErrorDomaincode且其NSFileWriteFileExistsErrordef conditional_remove(list, element, condition): if condition and element in list: list.remove(element) conditional_remove(column[x], sudo_prob[a][b][0], x != a) conditional_remove(line[x], sudo_prob[a][b][0], x != b) conditional_remove(square[x], sudo_prob[a][b][0], (x%3!=b%3) and (a%3!=0+(x>2)+(x>5))) ,则该路径中已存在该文件。