gpt4 book ai didi

ios - NSFileManager 移动文件显示错误

转载 作者:行者123 更新时间:2023-11-29 02:35:55 29 4
gpt4 key购买 nike

我正在尝试创建两个日志文件并将第二个文件中的内容替换为第一个文件中的内容。

我在 AppDelegate 中创建日志的代码

   NSArray *paths3 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory3 = [paths3 objectAtIndex:0];
logPath3 = [documentsDirectory3 stringByAppendingPathComponent:@"console4.log"];

if(![[NSFileManager defaultManager] fileExistsAtPath:logPath3])
[[NSFileManager defaultManager] createFileAtPath:logPath3 contents:[NSData data] attributes:nil];

NSLog(@"path %@",logPath3);

freopen([logPath3 cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr);

NSArray *paths2 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory2 = [paths2 objectAtIndex:0];
logPath2 = [documentsDirectory2 stringByAppendingPathComponent:@"console3.log"];

if(![[NSFileManager defaultManager] fileExistsAtPath:logPath2])
[[NSFileManager defaultManager] createFileAtPath:logPath2 contents:[NSData data] attributes:nil];

NSLog(@"path %@",logPath2);

freopen([logPath2 cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr);
_isFileOneCreated =YES;

移动内容的代码

NSFileManager *filemgr;
filemgr = [NSFileManager defaultManager];

NSError * err;
if ([filemgr moveItemAtPath:
logPath2 toPath:
logPath3 error: &err])
NSLog (@"Day 3 Move successful");
else
NSLog (@"Day 3 Move failed %@",[err localizedDescription]);

但我收到错误 516。

   (Cocoa error 516.)" UserInfo=0x16dba220    {NSSourceFilePathErrorKey=/var/mobile/Containers/Data/Application/274E9843-2C8E-45F3-BD41-EA392F50C7AC/Documents/console3.log, NSUserStringVariant=(
Move
), NSFilePath=/var/mobile/Containers/Data/Application/274E9843-2C8E-45F3-BD41-EA392F50C7AC/Documents/console3.log, NSDestinationFilePath=/var/mobile/Containers/Data/Application/274E9843-2C8E-45F3-BD41-EA392F50C7AC/Documents/console4.log, NSUnderlyingError=0x16da63f0 "The operation couldn’t be completed. File exists"}

帮我解决问题

最佳答案

moveItemAtPath 不允许您覆盖同名文件。看这个Question Thread .

您需要做的就是在用新文件覆盖之前删除目标位置的文件。使用下面的代码。这可以解决问题,但我建议您采取预防措施,备份您的文件,以防move 因某些未知原因无法正常工作。

NSFileManager *filemgr = [NSFileManager defaultManager];   
NSError * err;
[filemgr removeItemAtPath:logPath3 error:&err];
if ([filemgr moveItemAtPath:logPath3 toPath:logPath2 error: &err])
NSLog (@"Day 3 Move successful");
else
NSLog (@"Day 3 Move failed %@",[err localizedDescription]);

关于ios - NSFileManager 移动文件显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26374433/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com