Easy Tutorial
❮ Ios Tutorial Ios Gamekit ❯

IOS File Handling


Introduction

File handling cannot be directly explained through the application. We can understand IOS file handling through the following examples.

File operations in IOS. Because the application is in a sandbox, it is restricted in file read and write permissions and can only read and write files in a few directories.

Methods Used in File Handling

Below is a list of methods used to access and manipulate files.

You must replace the FilePath1, FilePath, and FilePath strings with the complete file path to achieve the desired operations.

Check if a file exists

NSFileManager *fileManager = [NSFileManager defaultManager];
// Get documents directory
NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [directoryPaths objectAtIndex:0];
if ([fileManager fileExistsAtPath:@""]==YES) {
    NSLog(@"File exists");
}

Compare the contents of two files

if ([fileManager contentsEqualAtPath:@"FilePath1" andPath:@"FilePath2"]) {
    NSLog(@"Same content");
}

Check if a file is writable, readable, or executable

if ([fileManager isWritableFileAtPath:@"FilePath"]) {
    NSLog(@"isWritable");
}
if ([fileManager isReadableFileAtPath:@"FilePath"]) {
    NSLog(@"isReadable");
}
if ([fileManager isExecutableFileAtPath:@"FilePath"]) {
    NSLog(@"is Executable");
}

Move a file

if ([fileManager moveItemAtPath:@"FilePath1" 
    toPath:@"FilePath2" error:NULL]) {
    NSLog(@"Moved successfully");
}

Copy a file

if ([fileManager copyItemAtPath:@"FilePath1" 
    toPath:@"FilePath2" error:NULL]) {
    NSLog(@"Copied successfully");
}

Delete a file

if ([fileManager removeItemAtPath:@"FilePath" error:NULL]) {
    NSLog(@"Removed successfully");
}

Read a file

NSData *data = [fileManager contentsAtPath:@"Path"];

Write to a file

[fileManager createFileAtPath:@"" contents:data attributes:nil];
❮ Ios Tutorial Ios Gamekit ❯