开发者

Writing to file in iOS using C/C++

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 per开发者_JS百科missions to write to and application B then reads from it. Or, forget application B, can I just open it and read?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜