2013-04-14 168 views
-1

我知道这可能看起来像一个一遍又一遍的问题,但我试图验证设备上存在的文件(位于支持文件夹中)的名称的文件是“names.txt”。从文件读取和写入

从我读过下面的代码应该工作,但我不断得到“文件未找到。”

NSFileManager *filemgr = [NSFileManager defaultManager]; 
NSString *path = @"names.txt"; 

if ([filemgr fileExistsAtPath:path]) { 

    NSLog (@"File exists"); 
} 
else { 
    NSLog (@"File not found"); 
} 
+3

是names.txt文件的完整路径吗? – bryanmac

回答

3

您需要文件的完整路径,而不仅仅是名称。

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES); 
NSString *appSupportDirectory = paths[0]; 
NSString *path = @"names.txt"; 
NSString *fullPath = [appSupportDirectory stringByAppendingPathComponent:path]; 

NSFileManager *filemgr = [NSFileManager defaultManager]; 
if ([filemgr fileExistsAtPath:fullPath]) { 

    NSLog (@"File exists"); 
} 
else { 
    NSLog (@"File not found"); 
} 

调整此代码以反映文件在应用程序中的实际完整路径。

+0

我将路径更改为:“/Users/user/Documents/folder/folder/projectname/names.txt”。 我不确定是否还有更多需要更改的内容,但这是我所能告诉的完整路径名称。 – joshft91

+0

@ joshft91这是iOS应用程序还是OS X程序?无论哪种方式,我不认为你想让你的代码有一个硬编码的路径到你的主目录。 – rmaddy

+0

这是一个iOS应用程序。而且,对,我不认为这就是我想要的,但我希望使用文件来读/写。 – joshft91