Looking at this code and offer some suggestions/criticism.
Note that GC is not yet covered. It's an answer to exercise 16.1 as follows.
Assumes that the files and directory reside in the current working directory.
Thanks in advance.
Note that GC is not yet covered. It's an answer to exercise 16.1 as follows.
Modify the copy program developed in Program 16.6 so that it can accept more than one source file to be copied into a directory, like the standard UNIX cp command. So, the command
$ copy copy1.m file1.m file2.m progs
should copy the three files copy1.m, file1.m, and file2.m into the directory progs. Be sure that when more than one source file is specified, the last argument is, in fact, an existing directory.
Assumes that the files and directory reside in the current working directory.
Thanks in advance.
Code:
#import <Foundation/NSObject.h>
#import <Foundation/NSFileManager.h>
#import <Foundation/NSString.h>
#import <Foundation/NSProcessInfo.h>
#import <Foundation/NSEnumerator.h>
#import <Foundation/NSAutoreleasePool.h>
#define ONEARGUMENT 1
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSFileManager *fm = [NSFileManager defaultManager];
NSProcessInfo *proc = [NSProcessInfo processInfo];
NSArray *args = [proc arguments];
BOOL isDirectory = NO, exists = NO;
NSString *working_directory, *destDir, *srcfile, *destfile;
NSInteger argCount;
NSLog(@"Current directory: %@", [fm currentDirectoryPath]);
/* check for correct usage */
if ( [[proc arguments] count] == ONEARGUMENT )
{
NSLog(@"Usage: file1, file2..., prog");
return 1;
}
/*check last argument is a directory */
working_directory = [ fm currentDirectoryPath];
destDir = [working_directory stringByAppendingPathComponent: [[proc arguments]lastObject ]];
exists = [ fm fileExistsAtPath: destDir isDirectory: &isDirectory];
if (!exists )
{
NSLog(@"Usage: Directory does not exist");
return 2;
}
if ( !isDirectory )
{
NSLog(@"Usage: Last file must be a Directory");
return 3;
}
/* iterate through[proc arguments] */
argCount = args.count;
int fileCount = 1;
while (--argCount > 1)
{
srcfile = [args objectAtIndex: fileCount++];
/*is source file readable */
if ( [ fm isReadableFileAtPath: srcfile] == NO)
{
NSLog(@"Error: Source file %@ is unreadable", srcfile);
return 4;
}
/*create destination path */
destfile = [ destDir stringByAppendingPathComponent: srcfile];
/* remove file if exists at destination */
[fm removeItemAtPath:destfile error:nil];
if ([fm copyPath:srcfile toPath:destfile handler:nil] == NO)
{
NSLog(@"Error: copy failed" );
return 5;
}
NSLog(@"Copy of %@ to %@ succeeded", srcfile, destfile);
NSLog(@"Contents of source:%@", [NSString stringWithContentsOfFile:srcfile encoding:NSUTF8StringEncoding error:nil]);
NSLog(@"Contents of destination:%@",[NSString stringWithContentsOfFile:destfile encoding:NSUTF8StringEncoding error:nil]);
}
[pool drain];
return 0;
}