2016-01-19 12 views
-3

我用writeToFile來創建input.txt文件,但沒有這個文件在項目的路徑中,我不知道我怎麼能找到它。我能找到這個文件在哪裏?

NSString* str2 = [NSString stringWithUTF8String:cstr]; 
[str2 writeToFile:@"input.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil]; 
NSString* str3 = [NSString stringWithContentsOfFile:@"input.txt" encoding:NSUTF8StringEncoding error:nil]; 
+2

您需要將完整路徑傳遞給'writeToFile:'。然後在讀取文件時使用相同的完整路徑。 – rmaddy

+1

而不是@「input.txt」傳遞該文件的路徑並寫入該文件。 –

+1

您的代碼將無法正常顯示。它會返回一個錯誤,並保存失敗。正如其他人指出的那樣,你需要傳遞一個完整路徑給'writeToFile:atomically:encoding:error:'的路徑參數。 Bori在下面的答案顯示瞭如何將文件保存到應用程序的文檔目錄,這是您可以在iOS中保存文件的有限數量的地方之一。 –

回答

3

ü需要一個路徑到您的應用程序文件夾添加到您的文件:

//get path to Documents 
NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 
//add path to you file name 
NSString *fileWithPath = [documentPath stringByAppendingPathComponent:@"input.txt"]; 
//then write 
[str2 writeToFile:fileWithPath atomically:TRUE encoding:NSUTF8StringEncoding error:NULL]; 

,那麼你就可以讀回過使用fileWithPath:

NSString* str3 = [NSString stringWithContentsOfFile:fileWithPath encoding:NSUTF8StringEncoding error:nil]; 
+0

這是正確的答案(投票)。對於OP,你應該接受這個答案。 –

相關問題