Writing to file in iOS using C/C++

ぃ、小莉子 提交于 2020-02-01 21:37:45

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/5341919/writing-to-file-in-ios-using-c-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!