Why does NSFileManager return TRUE on fileExistsAtPath when there is no such file?

最后都变了- 提交于 2019-12-25 07:58:52

问题


NSFilemanager is returning true for the following, when there should not be any such file there yet. What is happening?

    if([myManager fileExistsAtPath:[[self documentsDirectory] stringByAppendingPathComponent:@"Music/songlist.txt"]]){

NSLog(@"file is there");

}

回答1:


The documentation for NSFileManager seems to recommend not checking to see if files exist, and instead just trying to read the file and handle any errors gracefully (e.g. file not found error). What you are describing doesn't sound like a race condition—which is what the documentation's recommendation is trying to circumvent—but what happens if you just try to load the file rather than checking to see if it exists? You could, for example, try the following:

NSError *error;
NSStringEncoding encoding;
NSString *fileContents = [NSString stringWithContentsOfFile:fileName
                                               usedEncoding:&encoding
                                                      error:&error];

if (fileContents == nil)
{
    NSLog (@"%@", error);
}
else
{
    NSLog (@"%@", fileContents);
}

If you get a string with all of the file's contents, then the file is obviously there. If you get an error then something is up with myManager.




回答2:


Print this out and see if it is what you expect.

NSLog(@"Directory: %@", [[self documentsDirectory] stringByAppendingPathComponent:@"Music/songlist.txt"]];

Also, check that you are defining myManager correctly.




回答3:


This works as expected for me.

 NSFileManager *myManager = [NSFileManager defaultManager];
NSString *documentsDirectory = NSHomeDirectory();

if([myManager fileExistsAtPath:[documentsDirectory stringByAppendingPathComponent:@"Music/songlist.txt"]]){

    NSLog(@"file is there");

}


来源:https://stackoverflow.com/questions/2455735/why-does-nsfilemanager-return-true-on-fileexistsatpath-when-there-is-no-such-fil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!