The Foundation framework allows you to use the file system to perform basic operations on files or directories. These basic operations are provided by the NSFileManager class,
Methods of this class have the following functions:
- Create a new file
- Read data from existing files
- Write data to a file
- Rename a file
- Delete an object
- Whether the test file exists
- Determine the file size and other attributes
- Copy a file
- Test whether the content of the two files is the same
The preceding multi-data operations can also be performed directly on the directory. For example, you can create a directory, read the content, or delete the directory.
Manage files and directories
Each file method calls the NSFileManager object, and the NSFileManager object is created by sending a defaultManager message to the class,
As follows:
NSFileManager * fm
...
Fm = [NSFileManager defamanager manager];
For example, to delete a file named todolist from the current directory, first create an NSFileManager object (as shown above) and then call the removeFileAtPath method,
The Code is as follows:
[Fm removeFileAtPath: @ "todolist" handler: nil];
You can test the returned results to ensure that the files are deleted:
If ([fm removeFileAtPath: @ "todolist" handler: nil] = NO)
{
NSLog (@ "Couldn't remove file todolist ");
Return 1;
}
The following is an example of basic file operations:
// Basic ifle Operations <br/> // assumes the existence of a file called "testfile" <br/> // in ther current working directory <br/> # import <Foundation /nsobject. h> <br/> # import <Foundation/nsstring. h> <br/> # import <Foundation/nsfilemanager. h> <br/> # import <Foundation/NSAID utoreleasepool. h> <br/> # import <Foundation/nsdictionary. h> </P> <p> int main (INT argc, const char * argv []) <br/>{< br/> NSAID utoreleasepool * Pool = [[NSAID utoreleasepool alloc] init]; <br/> nsstring * fname = @ "testfile.txt"; <br/> nsfilemanager * FM; <br/> nsdictionary * ATTR; </P> <p> // need to create an instance of the File Manager <br/> fm = [nsfilemanager defaultmanager]; </P> <p> // Let's make sure our test file exists first <br/> If ([FM fileexistsatpath: fname] = No) <br/>{< br/> nslog (@ "file doesn't exist '"); <br/> return 1; <br/>}</ P> <p> // now let's make a copy </P> <p> If ([FM copypath: fname topath: @ "newfile.txt" handler: nil] = No) <br/>{< br/> nslog (@ "file copy failed"); <br/> return 2; <br/>}</P> <p> // Let's test to see if the two files are identical <br/> If ([FM contentsequalatpath: fname andpath: @ "newfile.txt"] = No) <br/>{< br/> nslog (@ "files are not equal! "); <Br/> return 3; <br/>}</P> <p> // now let's rename the copy </P> <p> If ([FM movepath: @ "newfile.txt" topath: @ "newfile2.txt" handler: Nil] = No) <br/>{< br/> nslog (@ "file rename failed! "); <Br/> return 4; <br/>}</P> <p> // get the size of newfile2 </P> <p> If (ATTR = [FM fileattributesatpath: @ "newfile2.txt" traverselink: No]) = nil) <br/>{< br/> nslog (@ "couldn't get file attributes! "); <Br/> return 5; <br/>}</P> <p> nslog (@" file size is % I bytes ", [ATTR objectforkey: nsfilesize] intvalue]); </P> <p> // and finally, let's Delete the original file <br/> If ([FM removefileatpath: fname handler: nil] = No) <br/>{< br/> nslog (@ "file removal failed! "); <Br/> return 6; <br/>}</P> <p> nslog (@" all operations were successful! "); </P> <p> // display the contents of the newly-created file </P> <p> nslog (@" % @ ", [nsstring stringwithcontentsoffile: @ "newfile2.txt" encoding: nsutf8stringencoding error: Nil]); </P> <p> [pool drain]; <br/> return 0; <br/>}< br/>
Use NSData class
When using files, you need to read data frequently into a temporary storage zone, which is usually called a buffer zone. When data is collected so that the data is subsequently output to a file,
The storage area is also used. The NSData class of Foundation provides a simple method to set the buffer area, read the file content into the buffer zone, or
Buffer content is written to a file.
The following is an example of using NSData:
# Import <Foundation/NSObject. h> <br/> # import <Foundation/NSString. h> <br/> # import <Foundation/NSFileManager. h> <br/> # import <Foundation/NSAID utoreleasepool. h> <br/> # import <Foundation/NSData. h> </p> <p> // make a copy of file <br/> int main (int argc, const char * argv []) <br/>{< br/> NSAID utoreleasepool * pool = [[NSAID utoreleasepool alloc] init]; <br/> NSFileManager * fm; <br/> NSData * fileData; </p> <p> fm = [NS FileManager defaultManager]; </p> <p> // Read the file newfile2 <br/> fileData = [fm contentsAtPath: @ "newfile2.txt"]; </p> <p> if (fileData = nil) <br/> {<br/> NSLog (@ "File read failed! "); <Br/> return 1; <br/>}</p> <p> // Write the data to newfile3 <br/> if ([fm createFileAtPath: @ "newfile3.txt" contents: fileData attributes: nil] = NO) <br/>{< br/> NSLog (@ "Couldn't create the copy! "); <Br/> return 2; <br/>}</p> <p> NSLog (@" File copy was successful! "); </P> <p> [pool drain]; <br/> return 0; <br/>}</p> <p>
Use directory
There are many methods to operate directories in the NSFileManager class.
The following is an example:
# Import <Foundation/nsobject. h> <br/> # import <Foundation/nsstring. h> <br/> # import <Foundation/nsfilemanager. h> <br/> # import <Foundation/NSAID utoreleasepool. h> </P> <p> int main (INT argc, const char * argv []) <br/> {<br/> NSAID utoreleasepool * Pool = [[NSAID utoreleasepool alloc] init]; <br/> nsfilemanager * FM; <br/> nsstring * dirname = @ "testdir"; <br/> nsstring * path; </P> <p> fm = [nsfilemanager defamanager Manager ]; </P> <p> // get current directory <br/> Path = [FM currentdirectorypath]; <br/> nslog (@ "Current directory path is % @", PATH ); </P> <p> // create a new directory <br/> If ([FM createdirectoryatpath: dirname attributes: Nil] = No) <br/>{< br/> nslog (@ "couldn't create directory! "); <Br/> return 1; <br/>}</P> <p> // rename the new directory <br/> If ([FM movepath: dirname topath: @ "newdir" handler: Nil] = No) <br/>{< br/> nslog (@ "directory rename failed! "); <Br/> return 2; <br/>}</P> <p> // change Directory into the new directory <br/> If ([FM changecurrentdirectorypath: @ "newdir"] = No) <br/>{< br/> nslog (@ "Change directory failed! "); <Br/> return 3; <br/>}</P> <p> // now get and display current working directory <br/> Path = [FM currentdirectorypath]; <br/> nslog (@ "Current directory path is % @", PATH); </P> <p> nslog (@ "all operations were successful! "); </P> <p> [pool drain]; <br/> return 0; <br/>}</P> <p>
Enumerate contents in the directory
Sometimes you need to enumerate the contents of a directory. You need to use the enumeratorAtPath: method or directoryContentsAtPath: Method to complete the enumeration process.
If you use the first method, you can enumerate each file in the specified directory at a time. By default, if one of the files is a directory, its content will also be recursively enumerated.
In this process, by sending a skipDescendants message to the enumerated object, the recursive process can be dynamically blocked and contents in the directory are not enumerated.
For directoryContentsAtPath: method, you can use this method to enumerate the contents of a specified directory and return the file list in an array.
If any file in this directory is itself a directory, this method does not recursively enumerate its content.
The following example shows how to use these two methods:
# Import <Foundation/NSArray. h> <br/> # import <Foundation/NSString. h> <br/> # import <Foundation/NSFileManager. h> <br/> # import <Foundation/NSAID utoreleasepool. h> </p> <p> // enumeratorAtPath: method and directoryContentsAtPath: Method <br/> // The difference is that the former traverses sub-directories, the latter does not traverse subdirectories <br/> int main (int argc, const char * argv []) <br/>{< br/> NSAID utoreleasepool * pool = [[NSAID utoreleasepool alloc] init]; <br/> NSFileManager * fm; <br/> NSString * pat H; <br/> NSDirectoryEnumerator * dirEnum; <br/> NSArray * dirArray; </p> <p> fm = [NSFileManager defamanager manager]; </p> <p> // Get current directory path <br/> path = [fm currentDirectoryPath]; </p> <p> // Enumerate the directory </p> <p> dirEnum = [fm enumeratorAtPath: path]; </p> <p> NSLog (@ "Contents of % @:", path); <br/> while (path = [dirEnum nextObject])! = Nil) <br/> NSLog (@ "% @", path ); </p> <p> // Another way to enumerate a directory <br/> dirArray = [fm directoryContentsAtPath: [fm currentDirectoryPath]; <br/> NSLog (@ "Contents using directoryContentsAtPath:"); </p> <p> for (int I = 0; I <[dirArray count]; I ++) <br/>{< br/> NSLog (@ "% @", [dirArray objectAtIndex: I]); <br/>}</p> <p> [pool drain]; <br/> return 0; <br/>}</p> <p>