2013-04-14 164 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