下面显示的函数在 Xcode 中运行良好,只要我在 OSX 应用程序中使用它们... 现在我编写了一个iOS应用程序,我想在.txt文件中保存一些数据并再次读取它们,但它不起作用...既没有写入文件,也没有读取文件... 我已经在网上搜索了解决方案,但我只找到了它在 OSX 应用程序中不起作用时的解决方案(错误的目录等...),但这不是我的情况,我已经让它工作了...
当我在 iOS 模拟器中使用它时有什么区别以及如何让它在那里运行?
//下面的代码现在是更正后的版本(在发布之前没有“缺少此内容”部分。
void SaveData(std::string FileName)
{
//!!this was missing
char *H = getenv("HOME");
std::string Home(H);
std::string FileName = Home + "/Documents/" + FileName;
std::ofstream FileOut (FileName);
if (FileOut.is_open())
{
//!!write data to file
FileOut.close();
}
}
void LoadData(std::string FileName)
{
//!!this was missing
char *H = getenv("HOME");
std::string Home(H);
std::string FileName = Home + "/Documents/" + FileName;
std::ifstream FileIn;
FileIn.open(FileName.c_str(), std::ios::in);
if(not FileIn.good())
{
//!!error message
return;
}
//!!read data from file
FileIn.close();
}
最佳答案
iOS 是沙盒的,限制了可以读取和写入的区域,并且 users/me/documents/xcodeprojects
不正确。
参见About the iOS File System了解详情。
您可以编写多个目录,文档目录可能就是您想要的。您必须进行调用才能获取路径,以下是 C++、Objective-C 和 Swift 中的调用示例:
C++(感谢:莫里茨·布赫蒂):
char *H = getenv("HOME");
std::string Home(H);
std::string FileName = Home + "/Documents/" + FileName;
对象:
NSArray *documentDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
swift :
let documentDirectoryPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as! String
关于iphone - XCode 7 - fstream 在 iPhone 模拟器中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35787778/