在iOS上用std编写文件

Pet*_*isu 3 c++ iphone stl file ios

我在xCode中添加了一个save.txt到我的iPhone资源,文本"..."

我写了一些字符串到文件,而不是阅读它,但当我读它,我只得到旧内容..所以没有新的写入其中

NSString* resources = [ [ NSBundle mainBundle ] resourcePath ] ;    

std::string respath( [ resources UTF8String ] ) ;

std::string fpath = respath + "/" + "save.txt" ;


std::ofstream file;

file.open(fpath.c_str(), std::ios::out );


file << "some text\n";

file.close();


std::ifstream rf;

rf.open(fpath.c_str(), std::ios::in );

char str[255];
while(rf) {
    rf.getline(str, 255);  

    if(rf) printf("%s", str);

}   
Run Code Online (Sandbox Code Playgroud)

Jul*_*rgé 12

您无法在应用程序包中编写或修改文件,file.open()调用肯定会失败,但您不会检查错误.相反,您应该写入应用程序的Documents文件夹.

根据您的代码示例,即:

NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                       NSUserDomainMask, YES);

NSString *documentsPath = [searchPaths objectAtIndex:0];

std::string respath( [ documentsPath UTF8String ] ) ;
Run Code Online (Sandbox Code Playgroud)