当文件名具有unicode(utf8)字符时,在ios 10.3中出现fopen问题

时间:2017-04-24 14:03:22

标签: ios utf-8 fopen ios10.3

我正在尝试在iOS 10.3的文档文件夹中创建一个名为'abcó.txt'的文件。 fopen()成功但文件未创建。知道为什么吗?以下是我的代码。

void test_fopen(){
    const char *docsFolder = [[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject] fileSystemRepresentation];
    std::string filePath = std::string(docsFolder) + "/abc";
    char oWithAcute[2] = {(char)0xC3, (char)0xB3, (char)0x00}; // the ó character to append
    filePath = filePath + oWithAcute + ".txt";
    FILE *fp = fopen(filePath.c_str(), "wb");
    NSLog(@"Trying to create file using fopen: %s", filePath.c_str());
    if( fp != NULL ){
        NSLog(@"fopen() SUCCEEDED.");
    }
    else {
        NSLog(@"fopen() FAILED.");
    }
    fclose(fp);

    NSFileManager* fm = [NSFileManager defaultManager];
    NSString *nsStr = [NSString stringWithUTF8String:filePath.c_str()];
    if (![fm fileExistsAtPath: nsStr]) {
        NSLog(@"File is NOT actually created.");
    }
    else{
        NSLog(@"File is actually created.");
    }
}

1 个答案:

答案 0 :(得分:3)

iOS 10.3使用新文件系统,请查看APFS is currently unusable with most non-English languages

因此需要使用高级Foundation API:

NSFileManager *fm = [NSFileManager defaultManager];
NSMutableData *data = [NSMutableData data];

...填写数据

[fm createFileAtPath:filePath contents:data attributes:nil];