Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing to file in iOS using C/C++

Tags:

c++

c

file-io

ios

Is it possible to create a text file using C/C++ calls in iOS? Is it then possible to open and read the file from outside the application? That is, application A creates a text file somewhere it has permissions to write to and application B then reads from it. Or, forget application B, can I just open it and read?

like image 676
341008 Avatar asked Mar 17 '11 16:03

341008


2 Answers

Since the question is explicitly asking for C/C++ and NOT Obj-C, I'm adding this 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 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 case you noticed about the "private" small difference, I wrote to both places and they happened to be the same.

like image 165
inigo333 Avatar answered Nov 13 '22 23:11

inigo333


Yes.

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

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

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

However, you can not access files of another App.

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

like image 20
BastiBen Avatar answered Nov 13 '22 23:11

BastiBen