Search code examples
iosobjective-cnsfilemanagernsdocumentdirectory

Creating a file with a file name which did not exist already in that folder using objective c


I would like to create a file in documents directory with name simpleFile.txt. Now if this simpleFile.txt already exists, I want to create to another file with the same name but appending the file number say simpleFile1.txt.


Solution

  • Use a while loop for this purpose like below

    NSFileManager *manager = [NSFileManager defaultManager];
    int i = 1;
    
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentPath = [documentPath objectAtIndex:0];
    NSString *newFileName = [documentPath stringByAppendingPathComponent:@"simpleFile.txt"];
    
    while ([manager fileExistsAtPath:newFileName]) {
        NSString *testName = [NSString stringWithFormat:@"simpleFile%d.txt", i];
        newFileName = [documentPath stringByAppendingPathComponent:testName];
        i++;
    }