2012-07-23 71 views
2

我嘗試在iPhone應用程序中使用fwrite(C函數)。ios fwrite函數EXC_BAD_ACCESS

由於自定義的原因,我不想使用writeToFile但是fwrite C函數。

didFinishLaunchingWithOptions寫了這個代碼功能:

FILE *p = NULL; 
    NSString *file= [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Hello.txt"]; 
    char buffer[80] = "Hello World"; 
    p = fopen([file UTF8string], "w"); 
    if (p!=NULL) { 
     fwrite(buffer, strlen(buffer), 1, p); 
     fclose(p); 
    } 

,但我得到的錯誤EXC_BAD_ACCESS在fwrite的功能。

任何幫助?

+0

檢查'fopen()'的返回值:無法打開文件時返回'NULL'。 – hmjd 2012-07-23 09:08:22

+0

我檢查它,它與NULL不同。我用代碼編輯我的帖子。 – TheFrancisOne 2012-07-23 09:10:55

+3

這個問題可能是愚蠢的,但是......爲什麼你不使用標準的'NSFileManager'或者使用'-writeToFile:atomically:encoding:error:'或'-writeToURL:atomically:encoding:error:'' NSString'對象...?不能保證你有權在iPhone上使用'fwrite()'函數將文件寫入沙盒中...... – holex 2012-07-23 09:12:55

回答

3

你的問題是你寫錯了地方。使用NSString類中提供的函數要容易得多,它允許你寫入一個文件。獲取到您的應用程序的沙箱/ Documents文件夾(你的應用程序的沙箱是唯一的地方,你都可以自由地寫入文件)

NSString *stringToWrite = @"TESTING"; 
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/filename.txt"]; 
[stringToWrite writeToFile:path atomically:YES encoding NSUTF8StringEncoding]; 

我覺得這是最簡單的方法。你可以用fwrite的一樣,你只需要將路徑轉換爲使用cstringUsingEncoding一個CString,像這樣:

NSString *stringToWrite = @"TESTING"; 
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/filename.txt"]; 
char *pathc = [path cStringUsingEncoding:NSUTF8StringEncoding]; 
char *stringToWritec = [stringToWrite cStringUsingEncoding:NSUTF8StringEncoding]; 

注:我幾乎可以肯定,蘋果使用UTF8編碼它的文件名。如果沒有,請嘗試NSASCIIStringEncoding和NSISOLatin1StringEncoding。

+0

我現在使用NSHomeDirectory(代碼編輯),我看到了創建的Hello.txt文件,但是爲空,並且在fwrite函數中仍然是EXC_BAD_ACCESS。 – TheFrancisOne 2012-07-23 09:37:00

+0

我真的想使用C函數「fwrite」,可以嗎? – TheFrancisOne 2012-07-23 09:37:18

+0

當然,唯一的問題是,fwrite收到一個c字符串,而不是一個NSstring。所以,在計算完路徑之後,您需要將字符串轉換爲一個c字符串。我會將代碼添加到我的答案中。 – 2012-07-23 09:42:07

相關問題