必须有一种更简单的方法来进行简单的字符串操作,而不是我正在进行的操作。我有一个方法,允许用户复制目录中的文件。如果他们在表视图中选择它并按下克隆按钮,则文件的副本将保存,fileName将附加子字符串Copy。如果Copy已经存在,那么我们需要迭代文件名并通过循环迭代附加文件名。例如;
<filename> Copy 1
<filename> Copy 2
until my other method return that the name is unique.
我需要检查三个标准的传入文件名; 它是否已经附加了“复制” 它是否已经附加了一个字符串编号 如果是这样,获取数字的值迭代它并将其重新放回。
过了一段时间,我只想出这个:
//Tokenize the string
NSArray *filenameArray =[copyName componentsSeparatedByString:@" "];
//Make sure the name is unique
//Update the namesArray
[self montageNameList];
int i = 1;
for(NSString * name in self.montageNames){
if([channelSetManager_ checkNoDuplicateName:self.montageNames forThisName:copyName]== YES){
break;
}else{
if([[filenameArray lastObject]isEqualToString:@"Copy"]){
//Just add a number to the end of the string
copyName = [copyName stringByAppendingFormat:@" %d", i];
}else if(([[filenameArray lastObject]intValue] > -1) && ([[filenameArray lastObject]intValue] < 100)){
i = [[filenameArray lastObject]intValue]+1;
NSInteger len = [[filenameArray lastObject]length]+1;
copyName = [copyName substringToIndex:[copyName length] - len ];
copyName = [copyName stringByAppendingFormat:@" %d",i];
}
}
}
这有效,但似乎不是正确的方法。非常感谢任何建议。
答案 0 :(得分:0)
过去我使用mkstemp()
创建了一个临时文件,然后将临时文件链接到永久文件,如果链接失败且文件存在则尝试下一个文件名,重复直到链接成功,并取消链接临时文件文件。
// Finds next available copy name and creates empty file as place holder
- (NSString *) createCopyFileWithBasename:(NSString *)baseName andSuffix:(NSString *)suffix
{
char tmpFile[1024];
char copyFile[1024];
int fd;
int count;
// create unique temporary file
snprintf(tmpFile, 1024, "%s.XXXXXXXX", [baseName UTF8String]);
if ((fd = mkstemp(tmpFile)) == -1)
{
NSLog(@"mkstemp(): %s", strerror(errno));
return(nil);
};
close(fd);
// attempt to create empty file for file copy
snprintf(copyFile, 1024, "%s Copy.%s", [baseName UTF8String], [suffix UTF8String]);
switch(link(tmpFile, copyFile))
{
case EEXIST: // file exists, skip to next possible name
break;
case: 0: // excellent, we found an available file name
unlink(tmpFile);
return([NSString stringWithUTF8String:copyFile]);
default:
NSLog(@"link(): %s", strerror(errno));
unlink(tmpFile);
return(nil);
};
// loop through possible iterations of file copy's name
for(count = 1; count < 1024; count++)
{
snprintf(copyFile, 1024, "%s Copy %i.s", [baseName UTF8String], count, [suffix UTF8String]);
switch(link(tmpFile, copyFile))
{
case EEXIST: // file exists, skip to next possible name
break;
case: 0: // excellent, we found an available file name
unlink(tmpFile);
return([NSString stringWithUTF8String:copyFile]);
default:
NSLog(@"link(): %s", strerror(errno));
unlink(tmpFile);
return(nil);
};
};
unlink(tmpFile);
NSLog(@"link(): %s", strerror(errno));
return(nil);
}
使用示例:
NSString copyFileName = [self createCopyFileWithBasename:@"My Data" andSuffix:@".txt"];