Inherits from: NSObject
Conforms to: NSObject
(NSObject)
NSCopying (NSObject)
Declared in: Foundation/NSFileManager.h
NSFileManager enables you to perform many generic file-system operations. With it you can:
Besides offering a useful range of generic functionality, the NSFileManager API insulates an application from the underlying file system. An important part of this insulation is the encoding of file names (in, for example, Unicode, ISO Latin1, and ASCII). This insulating layer makes it easier to port the application between operating systems with different file systems. There is a default NSFileManager object for the file system; this object responds to all messages that request a operation on the associated file system.
The pathnames specified as arguments to NSFileManager methods can be absolute or relative to the current directory (which you can determine with currentDirectoryPath and set with changeCurrentDirectoryPath:). However, pathnames cannot include wildcard characters.
On file systems on Rhapsody and supported UNIX systems, an absolute pathname starts with the root directory of the file system, represented by a slash (/), and ends with the file or directory that the pathname identifies. A relative pathname is relative to the current directory, the directory in which you are working and in which saved files are currently stored (if no pathname is specified). Relative pathnames start with a subdirectory of the current directory-without an initial slash-and end with the name of the file or directory the pathname identifies. |
Key | Value Type |
NSFileModificationDate | NSDate |
NSFilePosixPermissions | NSNumber |
The NSFilePosixPermissions value must be initialized with the code representing the POSIX file-permissions bit pattern.
You can change single attributes or any combination of attributes; you need not specify keys for all four attributes.
See Also: - fileAttributesAtPath:traverseLink:
- (NSData *)contentsAtPath:(NSString *)path
nil
.See Also: - contentsEqualAtPath:andPath:, - createFileAtPath:contents:attributes:
- (BOOL)contentsEqualAtPath:(NSString *)path1 andPath:(NSString
*)path2
See Also: - contentsAtPath:
- (BOOL)copyPath:(NSString *)source
toPath:(NSString *)destination
handler:handler
If the copy operation is successful, the method returns YES. If the operation is not successful, but the callback handler of fileManager:shouldProceedAfterError: returns YES (see below), copyPath:toPath:handler: also returns YES. Otherwise this copy method returns NO. The method also attempts to make the attributes of the directory or file at destination identical to source, but ignores any failure at this attempt.
handler identifies
an object that responds to the callback messages fileManager:willProcessPath: and fileManager:shouldProceedAfterError: (see
"Methods Implemented by the CallbackHandler," below). This callback
mechanism is similar to delegation. NSFileManager sends the first
message when it begins a copy, move, remove, or link operation.
It sends the second message when it encounters any error in processing.
You can specify nil
for handler if
no object responds to the callback messages. If you specify nil
and
an error occurs, the method automatically returns NO.
This code fragment verifies that the file to be copied exists and then copies that file to the user's ~/Library/Reports directory:
NSString *source = @"/tmp/quarterly_report.rtf"; NSString *destination = [[NSHomeDirectory() stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:@"Reports"]; NSFileManager *manager = [NSFileManager defaultManager]; if ([manager fileExistsAtPath:source]) [manager copyPath:source toPath:destination handler:nil];
See Also: - linkPath:toPath:handler:, - movePath:toPath:handler:, - fileManager:shouldProceedAfterError:, - removeFileAtPath:handler:, - fileManager:willProcessPath:
- (BOOL)createDirectoryAtPath:(NSString *)path
attributes:(NSDictionary *)attributes
nil
for attributes,
default values for these attributes are set (particularly write
access for creator and read access for others). The following table
lists the global constants used as keys in the attributes NSDictionary
and the types of the associated values:Key | Value Type |
NSFileModificationDate | NSDate |
NSFileOwnerAccountNumber | NSNumber |
NSFileGroupOwnerAccountNumber | NSNumber |
NSFilePosixPermissions | NSNumber |
See Also: - changeCurrentDirectoryPath:, - changeFileAttributes:atPath:, - createFileAtPath:contents:attributes:, - currentDirectoryPath
- (BOOL)createFileAtPath:(NSString *)path
contents:(NSData *)contents
attributes:(NSDictionary *)attributes
nil
for attributes,
the file is given a default set of attributes. The following table
summarizes the keys and types to associate with values in the NSDictionary attributes.Key | Value Type |
NSFileModificationDate | NSDate |
NSFileOwnerAccountNumber | NSNumber |
NSFileGroupOwnerAccountNumber | NSNumber |
NSFilePosixPermissions | NSNumber |
See Also: - contentsAtPath:, - changeFileAttributes:atPath:, - fileAttributesAtPath:traverseLink:
- (BOOL)createSymbolicLinkAtPath:(NSString *)path
pathContent:(NSString *)otherPath
See Also: - pathContentOfSymbolicLinkAtPath:, - linkPath:toPath:handler:
- (NSString *)currentDirectoryPath
nil
.Relative pathnames refer implictly to the current directory. For example, if the current directory is /tmp, and the relative pathname reports/info.txt is specified, the resulting full pathname is /tmp/reports/info.txt.
See Also: - createDirectoryAtPath:attributes:
- (NSArray *)directoryContentsAtPath:(NSString *)path
nil
if
the directory specified at path does
not exist or there is some other error accessing it. It returns
an empty array if the directory exists, but has no contents.The following example, generated by NSArray's description method, shows the results when this method is invoked on the directory /System/Developer.
Source, Makefiles, ProjectTypes, Applications, Java, PBBundles, Apps, Demos, Headers, Examples
See Also: - currentDirectoryPath, - fileExistsAtPath:isDirectory:, - enumeratorAtPath:, - subpathsAtPath:
- (NSDirectoryEnumerator *)enumeratorAtPath:(NSString
*)path
nil
. If path is
a filename, the method returns an enumerator object that enumerates
no files-the first call to nextObject will
return nil
.This code fragment enumerates the subdirectories and files under /MyAccount/Documents and processes all files with an extension of .doc:
NSString *file; NSDirectoryEnumerator *enumerator = [[NSFileManager defaultManager] enumeratorAtPath:@"/MyAccount/Documents"]; while (file = [enumerator nextObject]) { if ([[file pathExtension] isEqualToString:@"doc"]) [self scanDocument:file]; }
The NSDirectoryEnumerator class has methods for obtaining the attributes of the existing path and of the parent directory, and for skipping descendents of the existing path.
See Also: - currentDirectoryPath, - fileAttributesAtPath:traverseLink:, - directoryContentsAtPath:, - subpathsAtPath:
- (NSDictionary *)fileAttributesAtPath:(NSString
*)path traverseLink:(BOOL)flag
Key | Value Type |
NSFileSize (in bytes) | NSNumber |
NSFileModificationDate | NSDate |
NSFileOwnerAccountName | NSString |
NSFileGroupOwnerAccountName | NSString |
NSFileReferenceCount (number of hard links) | NSNumber |
NSFileIdentifier | NSNumber |
NSFileDeviceIdentifier | NSNumber |
NSFilePosixPermissions | NSNumber |
NSFileType | NSString |
The possible values for the NSFileType key are:
If flag is
YES and path is a symbolic link,
the attributes of the linked-to file are returned; if the link points
to a non-existant file, this method returns nil
.
If flag is NO, the attributes of
the symbolic link are returned.
This piece of code gets several attributes of a file and logs them.
NSNumber *fsize, *refs, *owner; NSDate *moddate; NSDictonary *fattrs = [manager fileAttributesAtPath:@"/tmp/List" traverseLink:YES]; if (!fattrs) { NSLog(@"Path is incorrect!"); return; } if (fsize = [fattrs objectForKey:NSFileSize]) NSLog(@"File size: %d\n", [fsize intValue]); if (refs = [fattrs objectForKey:NSFileReferenceCount]) NSLog(@"Ref Count: %d\n", [refs intValue]); if (moddate = [fattrs objectForKey:NSFileModificationDate]) NSLog(@"Modif Date: %@\n", [moddate description]);
As a convenience, NSDictionary provides a set of methods (declared as a category in NSFileManager.h) for quickly and efficiently obtaining attribute information from the returned NSDictionary: fileGroupOwnerAccountName, fileModificationDate, fileOwnerAccountName, filePosixPermissions, fileSize, fileSystemFileNumber, fileSystemNumber, and fileType. For example, you could rewrite the last statement in the code example above as:
if (moddate = [fattrs fileModificationDate]) NSLog(@"Modif Date: %@\n", [moddate description]);
See Also: - changeFileAttributes:atPath:
- (BOOL)fileExistsAtPath:(NSString *)path
See Also: - fileExistsAtPath:isDirectory:
- (BOOL)fileExistsAtPath:(NSString *)path isDirectory:(BOOL *)isDirectory
This example gets an NSArray that identifies the fonts in /System/Library/Fonts:
NSArray *subpaths; BOOL isDir; NSString *fontPath = @"/System/Library/Fonts"; NSFileManager *manager = [NSFileManager defaultManager]; if ([manager fileExistsAtPath:fontPath isDirectory:&isDir] && isDir) subpaths = [manager subpathsAtPath:fontPath];
See Also: - fileExistsAtPath:
- (NSDictionary *)fileSystemAttributesAtPath:(NSString
*)path
Key | Value Type |
NSFileSystemSize (in an appropriate unit, usually bytes | NSNumber |
NSFileSystemFreeSize (in an appropriate unit, usually bytes | NSNumber |
NSFileSystemNodes | NSNumber |
NSFileSystemFreeNodes | NSNumber |
NSFileSystemNumber | NSNumber |
The following code example checks to see if there's sufficient space on the file system before adding a new file to it:
const char *data = [[customerRec description] cString]; NSData *contents = [NSData dataWithBytes:data length:strlen(data)+1]; NSFileManager *manager = [NSFileManager defaultManager]; NSDictionary *fsattrs = [manager fileSystemAttributesAtPath:@"/Net/sales/misc"]; if ([[fsattrs objectForKey:NSFileSystemFreeSize] unsignedIntValue] > [contents length]) [manager createFileAtPath:@"/Net/sales/misc/custrec.rtf" contents:contents attributes:nil];
See Also: - fileAttributesAtPath:traverseLink:, - changeFileAttributes:atPath:
- (const char *)fileSystemRepresentationWithPath:(NSString
*)path
See Also: - stringWithFileSystemRepresentation:length:
- (BOOL)isDeletableFileAtPath:(NSString *)path
- (BOOL)isExecutableFileAtPath:(NSString *)path
- (BOOL)isReadableFileAtPath:(NSString *)path
- (BOOL)isWritableFileAtPath:(NSString *)path
- (BOOL)linkPath:(NSString *)source
toPath:(NSString *)destination
handler:handler
If source is a directory or symbolic link, this method copies it to destination instead of creating a hard link. The file, link, or directory specified in source must exist, while destination must not yet exist. The destination path must end in a file name; there is no implicit adoption of the source file name. Symbolic links in source are not traversed.
If the link operation is successful, linkPath:toPath:handler: returns YES. If the operation is not successful, but the handler method fileManager:shouldProceedAfterError: returns YES, the method also returns YES. Otherwise it returns NO.
The
argument handler identifies an object that responds to the callback
messages fileManager:willProcessPath: and fileManager:shouldProceedAfterError:f
(see "Methods Implemented by the Callback Handler," below).
This callback mechanism is similar to delegation. NSFileManager
sends the first message when it begins a copy, move, remove, or link
operation. It sends the second message when it encounters any error
in processing. You can specify nil for handler if no object responds
to the callback messages; if you specify nil
and
an error occurs, the method automatically returns NO.
This code fragment verifies the pathname typed in a text field (imageFileField) and then links the file to the user's ~/Library/Images directory:
NSString *imageFile = [imageFileField stringValue]; NSString *destination = [[NSHomeDirectory() stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:@"Images"]; NSFileManager *manager = [NSFileManager defaultManager]; if ([manager fileExistsAtPath:source]) [manager linkPath:source toPath:destination handler:self];
See Also: - copyPath:toPath:handler:, - createSymbolicLinkAtPath:pathContent:, - movePath:toPath:handler:, - fileManager:shouldProceedAfterError:, - removeFileAtPath:handler:, - fileManager:willProcessPath:
- (BOOL)movePath:(NSString *)source
toPath:(NSString *)destination
handler:handler
If the move operation is successful, the method returns YES. If the operation is not successful, but the handler method fileManager:shouldProceedAfterError: returns YES, movePath:toPath:handler: also returns YES; otherwise it returns NO. If a failure in a move operation occurs, the pre-existing path or the new path remains intact, but not both.
The argument
handler identifies an object that responds to the callback messages fileManager:willProcessPath: and fileManager:shouldProceedAfterError: (see
"Methods Implemented by the Callback Handler," below). This
callback mechanism is similar to delegation. NSFileManager sends
the first message when it begins a copy, move, remove, or link operation.
It sends the second message when it encounters any error in processing.
You can specify nil for handler if no object responds to the callback messages;
if you specify nil
and
an error occurs, the method automatically returns NO.
See Also: - copyPath:toPath:handler:, - linkPath:toPath:handler:, - removeFileAtPath:handler:, - fileManager:shouldProceedAfterError:, - fileManager:willProcessPath:
- (NSString *)pathContentOfSymbolicLinkAtPath:(NSString
*)cStringPath
See Also: - createSymbolicLinkAtPath:pathContent:
- (BOOL)removeFileAtPath:(NSString *)path handler:handler
The argument handler identifies an object that responds to the callback messages fileManager:willProcessPath: and fileManager:shouldProceedAfterError: (see "Methods Implemented by the Callback Handler," below). This callback mechanism is similar to delegation. NSFileManager sends the first message when it begins a copy, move, remove, or link operation. It sends the second message when it encounters any error in processing. You can specify nil for handler if no object responds to the callback messages; if you specify nil and an error occurs, the method automatically returns NO.
Since the removal of directory contents is so thorough and final, be careful when using this method. Do not specify "." or ".." for path; this will raise the exception NSInvalidArgumentException. This method does not traverse symbolic links.
See Also: - copyPath:toPath:handler:, - linkPath:toPath:handler:, - movePath:toPath:handler:, - fileManager:shouldProceedAfterError:, - fileManager:willProcessPath:
- (NSString *)stringWithFileSystemRepresentation:(const
char *)string
length:(unsigned int)len
See Also: - fileSystemRepresentationWithPath:
- (NSArray *)subpathsAtPath:(NSString *)path
Here is a sample fragment of what subpathsAtPath: returns (as the output of NSArray's description method) when path is /System/Developer:
Examples/Foundation/ForwardInvocation/PB.project, Examples/Foundation/ForwardInvocation/Makefile, Examples/Foundation/ForwardInvocation/TargetProxy.h, Examples/Foundation/ForwardInvocation/TargetProxy.m, Examples/Foundation/ForwardInvocation/ForwardInvocation_main.m, Examples/Foundation/MultiThreadedDO, Examples/Foundation/MultiThreadedDO/PB.project, Examples/Foundation/MultiThreadedDO/Makefile, Examples/Foundation/MultiThreadedDO/ThreadSafeQueue.h, Examples/Foundation/MultiThreadedDO/ThreadSafeQueue.m, Examples/Foundation/MultiThreadedDO/MultiThreadedDO_main.m,
Notice that this method reveals every element of the subtree at path, including the contents of file packages (such as applications, nib files, and RTFD files). This code fragment gets the contents of /System/Library/Fonts after verifying that the directory exists:
BOOL isDir=NO; NSArray *subpaths; NSString *fontPath = @"/System/Library/Fonts"; NSFileManager *manager = [NSFileManager defaultManager]; if ([manager fileExistsAtPath:fontPath isDirectory:&isDir] && isDir) subpaths = [manager subpathsAtPath:fontPath];
See Also: - directoryContentsAtPath:, - enumeratorAtPath:
The methods described in this section are methods to be implemented by the callback handler passed to several methods of NSFileManager.
- (BOOL)fileManager:(NSFileManager
*)manager
shouldProceedAfterError:(NSDictionary *)errorInfo
Key | Value |
@"Path" | The path related to the error (usually the source path) |
@"Error" | A description of the error |
@"ToPath" | The destination path (not all errors) |
Return YES if the operation (which is often continuous within a loop) should proceed and NO if it should not; the Boolean value is passed back to the invoker of copyPath:toPath:handler:, movePath:toPath:handler:, removeFileAtPath:handler: or linkPath:toPath:handler:. If an error occurs and your handler has not implemented this method, the invoking method automatically returns NO.
The following implementation of fileManager:shouldProceedAfterError: displays the error string in an attention panel and leaves it to the user whether to proceed or stop:
-(BOOL)fileManager:(NSFileManager *)manager shouldProceedAfterError:(NSDictionary *)errorDict { int result; result = NSRunAlertPanel(@"Gumby App", @"File operation error: %@ with file: %@", @"Proceed", @"Stop", NULL, [errorDict objectForKey:@"Error"], [errorDict objectForKey:@"Path"]); if (result == NSAlertDefaultReturn) return YES; else return NO; }
See Also: - fileManager:willProcessPath:
-(BOOL)fileManager:(NSFileManager
*)manager
willProcessPath:(NSString *)path