Question

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.

Was it helpful?

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++;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top