2012-04-10 88 views
5

我有一個使用C++類和FFmpeg的項目,我需要使用fopen並將文件寫入應用程序沙箱,因此我需要的代碼用C寫++是等價的:需要使用fopen在iOS項目的C++類中寫入文件

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *docs_dir = [paths objectAtIndex:0]; 

這會我去我的應用程序沙箱中,在那裏我幾乎可以操縱我的文件 的問題是,我怎麼去用C編寫這些代碼++,這樣我可以使用打開文件?

這是需要的方法實現:

int testGrabAndWrite(const char* streamURL, bool decode, const char* filename) 
{ 
    FILE *outfile; 
    int ret; 
    int counter = 0; 
    uint8_t *data;    // Pointer to the received audio mem 
    int size;     // Size of the received audio buffer 


    outfile = fopen(filename, "w"); 

    if (outfile == NULL) 
     exit(1); 

    // Open the RTP stream 
    if ((ret = openStream(streamURL, decode)) < 0) 
     return ret; 

    // Print out info about the stream found 
    int tmpSampleRate, tmpBitRate, tmpChannels; 
    ret = getStreamInfo(tmpSampleRate, tmpBitRate, tmpChannels); 
    printf("\nSample rate:%d Bit rateL%d Channels:%d\n",tmpSampleRate,tmpBitRate, tmpChannels); 

    // Grab some sample data and write it to file. 
    while (counter < 500) 
    { 
     ret = getStreamData(data, size); 
     fwrite(data, 1, size, outfile);        // Write RTP packets, i.e. mp3, to file. 
     printf("Wrote packet %d with size %d which returned %d. ", ++counter, size, ret); 
    } 

    fclose(outfile); 
    closeStream(); 

    return ret; 
} 
+2

'fopen()'是一個C API,而不是C++,它使用'fstream'類和朋友。向我們展示您需要整合的課程。 – trojanfoe 2012-04-10 14:29:30

+1

創建一個.mm文件..這樣你就可以同時使用C++和objective-c – 2012-04-10 14:31:14

回答

7
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *docs_dir = [paths objectAtIndex:0]; 
NSString* aFile = [docs_dir stringByAppendingPathComponent: @"somedocthatdefinitelyexists.doc"]; 

FILE* fp = fopen([aFile fileSystemRepresentation], "r"); 

-fileSystemRepresentation retruns一個char *適當地編碼以用於文件系統例如消息可能轉換爲UTF-8

+0

它工作得很好,謝謝 – 2012-04-10 15:53:37

+0

我注意到這適用於模擬器,但在4GS上文件返回爲null。不知道你們是否注意到了這一點。當我得到它時,嘗試添加解決方案。 – Dev2rights 2012-04-15 10:10:26

+0

@ Dev2Rights:除非文件丟失或不可讀,否則沒有理由說明上述代碼不適用於真實設備。 errno的價值是什麼? – JeremyP 2012-04-16 08:49:46