开发者

objective c,checking file exist at path

开发者 https://www.devze.com 2023-02-12 06:55 出处:网络
I have created a screen using Objective-C in an iPhone project. In that, there are 2 buttons (say A and B). On the click of button A, one xml file will be created in a folder (say INBOX).

I have created a screen using Objective-C in an iPhone project. In that, there are 2 buttons (say A and B). On the click of button A, one xml file will be created in a folder (say INBOX).

My problem is, I need to create 开发者_运维技巧the file only if it does not exist at folder INBOX. How can I do this? Can any one tell me the syntax?


Can you Please Check NSFileManager.

NSFileManager *fileManager = [NSFileManager defaultManager];

NSString *pathForFile;

if ([fileManager fileExistsAtPath:pathForFile]){ 

}


try this:

- (BOOL)checkAndCopy {
    NSError **error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"yourFile.xml"]; 

    NSFileManager *fileManager = [NSFileManager defaultManager];

    if (![fileManager fileExistsAtPath: path])
    {
        // this copy an existing xml (empty?) file from main bundle:
        // try else to create a new file

        NSString *bundle =  [[ NSBundle mainBundle] pathForResource:@"yourFile" ofType:@"xml"];
        [fileManager copyItemAtPath:bundle toPath:path error:error];
        return YES;
    }
    return NO;
}


There have been similar questions on SO before:

  1. This answer is probably most appropriate for you

Link to the NSFileManagerAPI

0

精彩评论

暂无评论...
验证码 换一张
取 消