Search code examples
iosnsfilemanager

NSFileManager moving a file shows error


I am trying to create two log files and replace content in the second file with the content in the first file.

My code for creating log in 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;

code to move content

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]);

But i get an error 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"}

Help me solve my issue


Solution

  • moveItemAtPath does not allow you to overwrite the file with same name. See this Question Thread.

    All you need to do is delete the file at target location before you overwrite with new one. Use the below code. This will do the trick but i advice you to take precaution to have the backup of your file just in case move doesn't work for some unknown reason.

    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]);