【问题标题】:Weird behavior of fopen on iosfopen 在 ios 上的奇怪行为
【发布时间】:2012-04-14 12:20:42
【问题描述】:

我正在尝试通过fopen创建一个文件然后写入它,但是发生了奇怪的事情。

  1. 当我将 iphone 插入 USB 端口时。一切正常。按预期在 tmp 目录或文档目录创建文件。
  2. 当我关闭设备并做同样的事情时,文件没有出现。我想知道为什么。

我使用 fopen 创建文件。就我而言,我应该这样做来创建然后写入文件。调用是 fopen(pcm_output, "wb+");

【问题讨论】:

  • 这段代码是用于ios还是插入本机系统?
  • 我想是的。否则即使插入也无法工作
  • 我也收到了这个“3 月 17 日 21:42:45 未知的 CommCenter[23] :MessageCenterModel 正在告诉 PDP 上下文 -1 进入活动状态。3 月 17 日 21:42:45 未知的沙盒 [ 3933] :ZhiJia_Listen(3916) 拒绝文件-写入-创建/�6"

标签: objective-c c ios


【解决方案1】:

你需要使用这个调用。

    char const *path = [fileManager fileSystemRepresentationWithPath:url.path];

来自文档...

fileSystemRepresentationWithPath: - (const char *)fileSystemRepresentationWithPath:(NSString *)path

iOS(2.0 及更高版本)

返回给定路径的 C 字符串表示,该路径正确编码 Unicode 字符串以供文件系统使用。

path:包含文件路径的字符串对象。 正确编码 Unicode 字符串以供文件系统使用的路径的 C 字符串表示形式。

【讨论】:

  • 谢谢,它有效。我想知道为什么这种方法有效,为什么 NSUTF8StringEncoding 无效。
  • 这将创建正确的编码,但请记住,文件系统不喜欢任何字符。这就是为什么他们有一种特殊的方法来为文件系统生成 char* 版本。
【解决方案2】:

您可能在沙盒之外编写,您可以发布路径吗? 就像一个测试尝试为您的应用打开 iTunes 共享(这应该没有效果,这只是一个测试)。

编辑:

经过测试我发现你必须使用:

NSString *docsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *filePath = [docsPath stringByAppendingPathComponent:[NSString stringWithCString:pcm_output encoding:NSUTF8StringEncoding]];    
fopen([filePath UTF8String], "wb+");

不仅仅是:

fopen([filePath UTF8String], "wb+");

【讨论】:

  • 你好,我在这个路径下写了文件“/var/mobile/Applications/ED98116B-BD1E-4319-B473-A699DB6B9F86/Documents”我相信它在沙箱里面。反正我会试试你的方法。
  • 感谢@fbernardo,但它不起作用。我想知道这是否与越狱有关。
【解决方案3】:
NSArray *paths = NSSearchPathForDirectoriesInDomains(
                                                 NSDocumentDirectory, 
                                                 NSUserDomainMask, YES
                                                 ); 
NSString* docDir = [paths objectAtIndex:0];
_tempLogPath = [docDir stringByAppendingPathComponent: @"Aisound5_CBLog.log"];
_tempPcmPath = [docDir stringByAppendingPathComponent: @"OutPcm.pcm"];
_tempWavPath = [docDir stringByAppendingPathComponent: @"OutWav.wav"];


tts_resource = [[bundle pathForResource:@"Resource_dev" ofType:@"irf"] UTF8String];
tts_log = [_tempLogPath UTF8String];
pcm_output = [_tempPcmPath UTF8String];
wav_output = [_tempWavPath UTF8String];

原代码是这样的,其中tts_resource tts_log pcm_output 和wav_output 定义在一个.h 文件中,用fopen 放在一个.c 文件中。

我曾尝试以您的方式使用显式 const char* 样式初始化 const 字符串,但问题仍然存在。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-23
    • 2014-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-13
    相关资源
    最近更新 更多