Iphone 在iOS上使用std写入文件

Iphone 在iOS上使用std写入文件,iphone,c++,ios,file,stl,Iphone,C++,Ios,File,Stl,我在xCode中将save.txt添加到我的iPhone资源中,并使用相同的文本“…” 我在文件中写入一些字符串,然后再读取它,但是当我读取它时,我只得到旧的内容。。所以这里面没有什么新的内容 NSString* resources = [ [ NSBundle mainBundle ] resourcePath ] ; std::string respath( [ resources UTF8String ] ) ; std::string fpath = respath + "/

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

}   
NSString*resources=[[NSBundle mainBundle]resourcePath];
std::string respath([resources UTF8String]);
std::string fpath=respath+“/”+“save.txt”;
流文件的std::of;
open(fpath.c_str(),std::ios::out);

文件您在写入时从不检查错误。事实上,您没有写入该文件,如果选中,错误代码可能会告诉您比我的答案更多的错误信息。

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

根据您的代码示例,这将是:

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

NSString *documentsPath = [searchPaths objectAtIndex:0];

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

当使用Objto-C时,为什么使用C++至少是一千万倍?你真的必须用STD来做吗?在我看来,使用NSString类更容易做到这一点:-如果你有一款永不出故障、永不耗尽空间的“神奇”iPhone,你应该检查错误,因为它可能是跨平台的