在iOS上用std编写文件

问题描述

| 我在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);

}   
    

解决方法

您不能在应用程序捆绑包内写入或修改文件,该file.open()调用肯定会失败,但您没有在检查错误。相反,您应该写入应用程序的Documents文件夹。 根据您的代码示例,将为:
NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);

NSString *documentsPath = [searchPaths objectAtIndex:0];

std::string respath( [ documentsPath UTF8String ] ) ;
    ,编写时,您永远不会检查错误。实际上,您并没有写该文件,如果检查了错误代码,可能会比我的回答更清楚地告诉您有关错误的信息。