With the iPhone/iPad it is possible to use the <stdio.h> facilities (..???). So you can use the fopen(), fgets(), fputs() functions and all the other functions in the <stdio.h> header file.


At beginning the use of the stdio functions seems to be good, but the ios sdk provides very powerful and useful functions to create/remove/access files in the idevices.

Before using the functions provided by the ios sdk you should understand the filesystem and the tree directories used in the iDevices. You can find a lot of information here……………….

Anyway, in brief, 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.


In this article I'll show essentially five 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<count; i++)

    {

        produced.text = [produced.text stringByAppendingString:[directoryContent objectAtIndex:i]];

        produced.text = [produced.text stringByAppendingString:@"\n"];

    }

}



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];

}

 

 

If you found useful this article, please share it using the social buttons below.

Thank you in advance,

Gg1.