Writing files using std on iOS

I added the save.txt file to my iPhone resource in xCode, with the same text "..."

I write some lines to a file and then read it, but when I read it, I only get the old contents. Therefore, it is nothing new.

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

}   
+3
source share
2 answers

You cannot write or modify files inside the application package, this call to file.open () certainly fails, but you do not check for errors. Instead, you should write to the Documents folder for your application.

In your example code that will look like this:

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

NSString *documentsPath = [searchPaths objectAtIndex:0];

std::string respath( [ documentsPath UTF8String ] ) ;
+12
source

. , , , , , , .

+1

All Articles