2012年5月26日 星期六

path operations

refer to  Addison Wesley - Programming.in.ObjectiveC.2.0.2nd (2009)

#import <Foundation/NSString.h>
#import <Foundation/NSArray.h>
#import <Foundation/NSFileManager.h>
#import <Foundation/NSAutoreleasePool.h>
#import <Foundation/NSPathUtilities.h>

int main (int argc, char *argv[])
{
NSAutoreleasePool  * pool = [[NSAutoreleasePool alloc] init];
NSString           *fName = @ ” path.m ” ;
NSFileManager      *fm;
NSString           *path, *tempdir, *extension, *homedir, *fullpath;
NSString           *upath = @ ” ~stevekochan/progs/../ch16/./path.m ” ;
NSArray            *components;

fm = [NSFileManager defaultManager];

// Get the temporary working directory
tempdir = NSTemporaryDirectory ();
NSLog (@ ” Temporary Directory is %@ ” , tempdir);

// Extract the base directory from current directory
path = [fm currentDirectoryPath];
NSLog (@ ” Base dir is %@ ” , [path lastPathComponent]); //檔案所在的目錄

// Create a full path to the file fName in current directory
fullpath = [path stringByAppendingPathComponent: fName];
NSLog (@ ” fullpath to %@ is %@ ” , fName, fullpath);

// Get the file name extension
extension = [fullpath pathExtension];
NSLog (@ ” extension for %@ is %@ ” , fullpath, extension);

// Get user ’ s home directory
homedir = NSHomeDirectory ();
NSLog (@ ” Your home directory is %@ ” , homedir);

// Divide a path into its components
components = [homedir pathComponents];
for ( path in components)
  NSLog (@ ” %@ ” , path);  //將目錄下的檔案列出

// “ Standardize ” a path 簡化path,
NSLog (@ ” %@ => %@ ” , upath , [upath stringByStandardizingPath] );

[pool drain];
return 0;


Temporary Directory is /var/folders/HT/HTyGLvSNHTuNb6NrMuo7QE+++TI/-Tmp-/
Base dir is examples
fullpath to path.m is /Users/stevekochan/progs/examples/path.m
extension for /Users/stevekochan/progs/examples/path.m is m
Your home directory is /Users/stevekochan
/
Users
stevekochan
~stevekochan/progs/../ch16/./path.m => ~stevekochan/ch16/path.m

沒有留言: