C++ 我可以在IOS中使用tempnam吗?

C++ 我可以在IOS中使用tempnam吗?,c++,objective-c,ios,C++,Objective C,Ios,我将C++ LIB移植到iOS,并遇到了一个代码调用TMPNM的问题。该函数返回“var/tmp/tmp.0.0xGlzv”,我假设它不在允许我的应用程序在其中播放的“沙箱”中。子序列fopen返回“不允许操作”。有可行的替代品吗?怎么样 [NSTemporaryDirectory() stringByAppendingPathComponent:@"myTempFile1.tmp"]; ? 要获得唯一的文件名,请尝试以下操作: NSString *uniqueTempFile() {

我将C++ LIB移植到iOS,并遇到了一个代码调用TMPNM的问题。该函数返回“var/tmp/tmp.0.0xGlzv”,我假设它不在允许我的应用程序在其中播放的“沙箱”中。子序列fopen返回“不允许操作”。有可行的替代品吗?

怎么样

[NSTemporaryDirectory() stringByAppendingPathComponent:@"myTempFile1.tmp"];
?

要获得唯一的文件名,请尝试以下操作:

NSString *uniqueTempFile()
{
    int i = 1;
    while (YES)
    {
        NSString *currentPath = [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"%i.tmp", i]];
        if (![[NSFileManager defaultManager] fileExistsAtPath:currentPath])
            return currentPath;
        else
        {
            i++;
        }
    }
}

这很简单,但可能不是内存效率最高的答案。

我不知道有什么替代方法可以用于iostreams,但请记住,如果使用返回您稍后打开的名称的函数,则会使您面临竞争条件,即另一个进程在您的程序确定该文件不存在的同时打开该文件


更安全的方法是使用类似
tmpfile
(man-tmpfile)的东西,不幸的是它返回了一个C风格的
文件*
,而不允许您使用iostreams。然而,编写一个使用stringstream包装的类,然后将该流的内容作为文本写入
文件*

我相信这是您真正想要的(文件没有扩展名,所以如果需要,可以附加一个扩展名):


这是我用的。此外,这是为了在不调用函数的情况下进行内联复制/粘贴而设置的

- (NSString *)tempFilePath
{
    NSString *tempFilePath;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    for (;;) {
        NSString *baseName = [NSString stringWithFormat:@"tmp-%x.caf", arc4random()];
        tempFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:baseName];
        if (![fileManager fileExistsAtPath:tempFilePath])
            break;
    }
    return tempFilePath;
}

这让我进入了沙箱可接受的区域。现在来生成一个唯一的文件名。这里有一个提示-永远不要在C
模板中命名变量。它会导致太多的错误,你需要与C++在路上的交互。@ RICHARJ.R.S.sisiii,我明白你的意思了-抱歉,这只是示例代码。我会解决它。你的函数应该
返回tempFilePath:)
- (NSString *)tempFilePath
{
    NSString *tempFilePath;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    for (;;) {
        NSString *baseName = [NSString stringWithFormat:@"tmp-%x.caf", arc4random()];
        tempFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:baseName];
        if (![fileManager fileExistsAtPath:tempFilePath])
            break;
    }
    return tempFilePath;
}