場景:導出數據到本地,以文件夾格式和文件名格式導出,數據中存在同名問題,爲了防止不覆蓋,要創建一個新的文件夾或者文件名用以區分同名的不同數據。
下面編寫一個小例子進行說明:
DirAndFile.h
#import <Foundation/Foundation.h>
@interface DirAndFile : NSObject
+(NSString*) getDirPathNewName:(NSString*)path;
+(NSString*) getFilePathNewName:(NSString*)path withPosfix:(NSString*)posfix;
@end
DirAndFile.m
#import "DirAndFile.h"
@implementation DirAndFile
//路徑中存在同名目錄,創建一個新的目錄名
+(NSString*) getDirPathNewName:(NSString*)path
{
NSFileManager* manager = [NSFileManager defaultManager];
NSString* tempPath =path;
NSString* tempDirPath =@"";
NSRange range = [path rangeOfString:@"/" options:NSBackwardsSearch];
range.length = range.location;
range.location = 0;
tempDirPath = [path substringWithRange:range];
//獲取目錄最後一個目錄名稱
NSString* name=[path lastPathComponent];
int count = 1;
BOOL isDir =NO;
while (true)
{
// 判斷目錄是否存在
BOOL isExistDir =[manager fileExistsAtPath:tempPath isDirectory:&isDir];
if (isDir && isExistDir)
{
if ([name rangeOfString:@"(" options:NSCaseInsensitiveSearch].location != NSNotFound)
{
NSRange range = [name rangeOfString:@"(" options:NSBackwardsSearch];
range.length = range.location;
range.location = 0;
name = [name substringWithRange:range];
}
name =[name stringByAppendingFormat:@"(%d)",count];
tempPath =[tempDirPath stringByAppendingPathComponent:name];
isDir =NO;
++count;
}
else
{
break;
}
}
return tempPath;
}
//路徑中存在同名文件名,創建一個新的文件名
+(NSString*) getFilePathNewName:(NSString*)path withPosfix:(NSString*)posfix
{
NSAutoreleasePool *pool = [NSAutoreleasePool new];
NSFileManager* manager = [NSFileManager defaultManager];
int count = 1;
NSRange range = [path rangeOfString:@"." options:NSBackwardsSearch];
range.length = range.location;
range.location = 0;
NSString* namePart = [path substringWithRange:range];
NSString* temp = namePart;
while (YES)
{
temp = [temp stringByAppendingString:posfix];
if (![manager fileExistsAtPath:temp])
{
[temp retain];
break;
}
temp = [namePart stringByAppendingFormat:@"(%d)",count++];
}
[pool drain];
return temp;
}
@end
main.m
#import <Foundation/Foundation.h>
#import "DirAndFile.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
//存在同名目錄名稱時,在目錄後添加一個數字標記區分同名目錄。
NSString *dirPath =@"/Users/mac/work/test-dir(2)";
NSFileManager *fm =[NSFileManager defaultManager];
for (int i =0; i<5; ++i)
{
NSString *tempDir =[dirPath stringByAppendingPathComponent:@"aa"];
tempDir= [DirAndFile getDirPathNewName:tempDir];
[fm createDirectoryAtPath:tempDir withIntermediateDirectories:NO attributes:nil error:nil];
NSLog(@"dir%d:%@",i+1,tempDir);
}
//存在同名文件名稱,文件名後添加數字標識
FILE *file =NULL;
for (int i =0; i<5; ++i)
{
NSString* filePath =[dirPath stringByAppendingPathComponent:@"content.txt"];
filePath =[DirAndFile getFilePathNewName:filePath withPosfix:@".txt"];
file =fopen([filePath UTF8String], "w");
if (file == NULL)
{
break;
}
NSString *content=@"hello world";
fwrite([content UTF8String], strlen([content UTF8String]), 1, file);
fclose(file);
}
}
return 0;
}
運行結果: