Search code examples
objective-cmacosnsurlnsfilemanagerfile-copying

copyItemAtPath:toPath:error: is returning NO


The chapter I'm reading is talking about NSFileManager, and the author said to create an empty file called testFile. The testFile is under the same folder as main.m. I didn't create newfile. I'm not able to copy testFile, and it's returning 2 and a NSLog saying @"couldnt copy file". I tried to put the argument for toPath: as @"/Users/el/Desktop/prog/prog/newfile"

int main (int argc, char *argv[]) {
    @autoreleasepool {
        NSString *fName = @"/Users/el/Desktop/prog/prog/testFile";
        NSFileManager *fm = [NSFileManager defaultManager];

        if ([fm fileExistsAtPath: fName] == NO) {
            NSLog(@"couldnt find file");
            return 1;
        }

        if ([fm copyItemAtPath:fName toPath:@"newfile" error:NULL] == NO) {
            NSLog(@"couldnt copy file");
            return 2;
        }

Solution

  • The second path must be also absolute.

    [fm copyItemAtPath: @"/Users/el/Desktop/prog/prog/testFile" toPath: @"/Users/el/Desktop/prog/prog/newFile" error: NULL];
    

    Note: You should use the NSURL-based methods instead of the NSString-based ones.