I added a check to see if the destination exists or is a directory
main.m#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSFileManager *fm = [NSFileManager defaultManager];
NSString *dest;
NSProcessInfo *proc = [NSProcessInfo processInfo];
NSArray *args = [proc arguments];
NSMutableArray *source = [NSMutableArray array];
BOOL isDir;
int i;
if (argc < 3)
{
NSLog(@"Usage: %@ src dest", [proc processName]);
return 1;
}
for(i = 1; i < argc-1; ++i)
{
[source addObject: [args objectAtIndex: i]];
}
for( NSString *temp in source)
{
dest = [args lastObject];
if (![fm isReadableFileAtPath: temp])
{
NSLog(@"Can't read %@", temp);
return 2;
}
[fm fileExistsAtPath:dest isDirectory:&isDir];
if (!isDir) // Added a check to see if the destination is a directory or even exists
{
NSLog(@"Destination is not a directory or doesn't exist!");
return 3;
}
dest = [dest stringByAppendingPathComponent: [temp lastPathComponent]];
[fm removeItemAtPath: dest error: NULL];
if (![fm copyItemAtPath: temp toPath: dest error: NULL])
{
NSLog(@"Copy failed!");
return 4;
}
NSLog(@"Copy of %@ to %@ succeeded!", temp, dest);
}
[pool drain];
return 0;
}
A question to skochan: Why didn't you use
argc in this chapter and used
[args count] instead?
I know you try to avoid low-level C stuff, but I think this was unnecesarry.