2012-07-26 79 views
1

我是IOS編程新手。我想將一些數據寫入文件。我已成功打開文檔路徑中的文件。但是它寫不出預期的效果。如果我打開它的空文件。它是我使用的我的代碼。我做錯了什麼。如何在IOS中編寫文件

typedef struct test { 
     int a; 
    } TEST_OBJ; 

    TEST_OBJ test_obj1; 
    test_obj1.a = 5; 
    TEST_OBJ *data_ptr = &test_obj1; 

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"MyFile1.txt"]; 

    //This is working fine. 
    // [data writeToFile:appFile atomically:YES]; 


    NSFileManager *fileManager = [[NSFileManager alloc]init]; 
    char const *path = [fileManager fileSystemRepresentationWithPath:appFile]; 


    FILE *fp = fopen(path, "w+b"); 


    // This write is not working. File is empty. 
    int cnt = fwrite (data_ptr , 1 , sizeof(test_obj1) , fp); 
    fclose(fp); 
    fp = NULL; 

任何人都可以告訴我我做錯了什麼?

+0

你只想寫一件事?堅持Obj-C ...在NSString和NSData上有方便的方法來寫入文件。 – borrrden 2012-07-26 09:52:12

+0

我有點困惑如何使用NSData編寫結構。你能給我一些建議嗎? – Feroz 2012-07-26 09:58:40

+0

看到我下面的評論 – borrrden 2012-07-26 10:01:31

回答

0

我已經改變了現在打開+它的寫作和正確閱讀模式。感謝你的幫助。

3

我建議您使用NSData而不是C函數。

NSData *myData = [[NSData alloc] initWithBytes:bytes length:length]; 
[myData writeToFile:path atomically:YES]; 
+0

將任何文件寫入沙箱丫我試過用NSData,它工作正常。然而,是否有可能寫一個結構呢? – Feroz 2012-07-26 09:53:48

+0

定義將其轉換爲字符串進行寫入的方法。 – borrrden 2012-07-26 09:57:17

+0

或者您可以將其轉換爲NSDictionary,然後將其寫入磁盤。 – DrummerB 2012-07-26 09:58:37

3

你可以使用NSData,NSArray,NSDictionary,它們有[writeToFile:atomically:]方法,它可以將數據寫入文件。

如果你必須C讀取和寫入文件流,你可以使用我的方法下面,它可以添加arrayString文件。

- (void)putArrayString:(NSString *)arrayString toFilePath:(NSString *)filePath 
{ 
    FILE *fileStream = fopen([filePath UTF8String], "a+"); 

    if(fileStream == NULL) 
    { 
     fclose(fileStream); 
     fileStream = fopen([filePath UTF8String], "w+"); 
     fputs([arrayString UTF8String], fileStream); 
    } 
    else 
    { 
     fputs([arrayString UTF8String], fileStream); 
    } 
    fclose(fileStream); 
} 
+0

它會工作的結構? – Feroz 2012-07-26 11:45:49