« 包含标签 iOS 的文章

[Repaste] how to read / write a file

There are two directories where you can store your data.

  1. tmp
  2. Documents

The first one will not be backupped by the iTunes, it can be used to store temporary data and when the program exits it should be cleaned.
The Documents directory will be backupped by iTunes and it can be used to store persistent data.

There’re five basic functions:

  1. How to save a file
  2. How to read a text file into a NSString
  3. How to list the contents of a directory.
  4. How to change the name of file.
  5. How to remove a file.

 

Saving a file.

This function extracts the complete path to the Documents directory and then append to this path the name of a file that the user give in an UIEditField. Then it checks if the file exists, if the file doesn’t exist the function creates the file and fill it with the text contained in the UITextView (source). If the file exists the function prints an error message in the UITextView (produced)

- (IBAction)saveFile:(id)sender
{
    NSArray       *myPathList        =  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString      *myPath            =  [myPathList  objectAtIndex:0];
    NSError       **err;
 
    myPath = [myPath stringByAppendingPathComponent:fileNameTextField.text];
    if(![[NSFileManager defaultManager] fileExistsAtPath:myPath])
    {
        [[NSFileManager defaultManager] createFileAtPath:myPath contents:nil attributes:nil];
        [source.text writeToFile:myPath atomically:NO encoding:NSUTF8StringEncoding error:err];
    }
    else
    {
        produced.text = @"Cannot overwrite existing files";
    }
}

 

Loading a file.

This function extracts the complete path to the Documents directory and then append to this path the name of a file that the user give in an UIEditField. Then it checks if the file exists, if the file exists the reads its content and put it into the UITextView (source). If the file doesn’t exist the function prints an error message on the debugger console.

- (IBAction)loadFile:(id)sender
{
    NSArray       *myPathList        =  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString      *myPath            =  [myPathList  objectAtIndex:0];
    NSError       **err;
 
    myPath = [myPath stringByAppendingPathComponent:fileNameTextField.text];
    if([[NSFileManager defaultManager] fileExistsAtPath:myPath])
        source.text = [NSString stringWithContentsOfFile:myPath encoding:NSUTF8StringEncoding error:err];
    else
    {
        printf("Errore");
    }
}

 

Listing files in a directory

This function extracts the complete path to the Documents directory, the it obtains the content of the directory using the function contentsOfDirectoryAtPath, than extracts the number of files in the directory using the function count, then it loops on the count variable and for each element in the directoryContents adds a line in the UITextView (produced).

- (IBAction)showFiles:(id)sender
{
    int           count, i;
    NSError       **err;
    NSArray       *directoryContent;
    NSArray       *myPathList        =  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString      *myPath            =  [myPathList  objectAtIndex:0];
 
    directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:myPath error: err];
    count = (int)[directoryContent count];
    for (i=0; i

 

Howto change the name of a file.

This function uses removeFileAtPath and movePath to change the name of a file.

- (IBAction)changeFileName:(id)sender
{
    NSFileManager *defaultManager;
    defaultManager = [NSFileManager defaultManager];
    NSString *fileToChange = @"/the/file/to/change";
    NSString *finalFilename;
    finalFilename = [NSString stringWithFormat: @"%@", fileNameTextField.text];
 
    // remove it first, otherwise the move will fail
    [defaultManager removeFileAtPath: finalFilename handler: nil];
 
    // now rename the file
    [defaultManager movePath: fileToChange toPath: finalFilename handler: nil];
}

This function can be easily modified to add an extension to a file, for example if we want to add a tilde at the end of the file name we can run the following code:

- (IBAction)addTildeAtTheEnd:(id)sender
{
    NSFileManager *defaultManager;
    defaultManager = [NSFileManager defaultManager];
    NSString *fileToChange = @"/the/file/to/change";
    NSString *finalFilename;
    finalFilename = [NSString stringWithFormat: @"%@~", fileToChange];
 
    // remove it first, otherwise the move will fail
    [defaultManager removeFileAtPath: finalFilename handler: nil];
 
    // now rename the file
    [defaultManager movePath: fileToChange toPath: finalFilename handler: nil];
}

Howto change the name of a file.

This function uses removeFileAtPath to remove a file.

- (IBAction)removeFile:(id)sender
{
    NSFileManager *defaultManager;
    defaultManager = [NSFileManager defaultManager];
    NSString *filename = @"/my/original/file/name";
    [defaultManager removeFileAtPath: filename handler: nil];
}

Evil Dead App

My first iOS game! 🙂
Kill zombies and save friends, kill and save….kill and save… @_@