[ACCEPTED]-Writing to file in iOS using C/C++-file-io

Accepted answer
Score: 26

Since the question is explicitly asking 6 for C/C++ and NOT Obj-C, I'm adding this 5 answer, which I saw here and might help someone:

char buffer[256];

//HOME is the home directory of your application
//points to the root of your sandbox
strcpy(buffer,getenv("HOME"));

//concatenating the path string returned from HOME
strcat(buffer,"/Documents/myfile.txt");

//Creates an empty file for writing
FILE *f = fopen(buffer,"w");

//Writing something
fprintf(f, "%s %s %d", "Hello", "World", 2016);

//Closing the file
fclose(f);

Using 4 this C code:

buffer = "/private/var/mobile/Containers/Data/Application/6DA355FB-CA4B-4627-A23C-B1B36980947A/Documents/myfile.txt"

While the Obj-C version:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

is returning

documentsDirectory = /var/mobile/Containers/Data/Application/6DA355FB-CA4B-4627-A23C-B1B36980947A/Documents

FYI, in 3 case you noticed about the "private" small 2 difference, I wrote to both places and they 1 happened to be the same.

Score: 7

Yes.

Use NSFileHandle to get read/write access to files 13 and NSFileManager to create directories and list their 12 contents and do all other sorts of file 11 system access.

Just keep in mind that every 10 App is sandboxed and can only write to its 9 own designated directories. You can get 8 the path to these directories with code 7 like this:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;

However, you can not access files 6 of another App.

iTunes automatically backs 5 up these directories, so they are automatically 4 restored if the user does a device restore. Also 3 keep in mind that you should not "expose" the 2 file system to the App users in form of 1 file-browsers or "save dialogs", etc.

More Related questions