Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing files with std on iOS

i added a save.txt to my iPhone resource in xCode, with a same text "..."

i write some strings to the file, and than read it, but when i read it, i only get the old content.. so there is nothing new written into it

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

}   
like image 836
Peter Lapisu Avatar asked Sep 06 '25 18:09

Peter Lapisu


1 Answers

You cannot write or modify files inside the application bundle, that file.open() call is surely failing but you aren't checking for errors. Instead, you should write to the Documents folder for your app.

Per your code sample, that would be:

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

NSString *documentsPath = [searchPaths objectAtIndex:0];

std::string respath( [ documentsPath UTF8String ] ) ;
like image 131
Julio Gorgé Avatar answered Sep 10 '25 07:09

Julio Gorgé