简体   繁体   中英

Need to write to a file using fopen in a C++ class for iOS project

I have a project that uses C++ classes and FFmpeg, I need to use fopen and write a file to the app sandbox, so the code that I need to write in C++ is the equivalent of:

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

This would me to my app sandbox, where I can pretty much manipulate my files The question is how do I go about writing this code in C++ so that I can use fopen on a file?

This is the method that needs implementation:

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;
}
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");

The message -fileSystemRepresentation retruns a char* suitably encoded for the file system eg probably converted to UTF-8

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM