【问题标题】:Need to write to a file using fopen in a C++ class for iOS project需要在 iOS 项目的 C++ 类中使用 fopen 写入文件
【发布时间】:2012-04-22 20:29:20
【问题描述】:

我有一个使用 C++ 类和 FFmpeg 的项目,我需要使用 fopen 并将文件写入应用沙箱,所以我需要用 C++ 编写的代码相当于:

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

这将是我的应用沙箱,在那里我几乎可以操作我的文件 问题是如何在 C++ 中编写此代码,以便可以在文件上使用 fopen?

这是需要实现的方法:

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

【问题讨论】:

  • fopen() 是一个 C API,而不是使用 fstream 类和朋友的 C++。向我们展示您需要集成的类。
  • 创建一个.mm文件..这样你就可以同时使用c++和objective-c

标签: iphone c++ objective-c ios ffmpeg


【解决方案1】:
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 重新运行为文件系统适当编码的 char*,例如可能转换为 UTF-8

【讨论】:

  • 我注意到这适用于模拟器,但文件在 4GS 上返回为 null。不知道你们是否注意到了这一点。当我得到它时,我会尝试添加解决方案。
  • @Dev2Rights:上面的代码没有理由不能在真实设备上运行,除非文件丢失或不可读。 errno的值是多少
猜你喜欢
  • 1970-01-01
  • 2011-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-07
  • 2014-06-29
  • 1970-01-01
相关资源
最近更新 更多