Nassif
Nassif

Reputation: 1223

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.

Upvotes: 2

Views: 430

Answers (1)

vignesh kumar
vignesh kumar

Reputation: 2330

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++;
}

Upvotes: 4

Related Questions