在iOS上用std编写文件

Writing files with std on iOS

本文关键字:文件 std iOS 上用      更新时间:2023-10-16

我在xCode中向我的iPhone资源添加了一个save.txt,带有相同的文本"…"

我在文件中写了一些字符串,然后读了它,但当我读它时,我只得到旧的内容。。所以中没有任何新内容

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 textn";
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 ] ) ;

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