在iOS中,是否可以使用C/C++调用创建文本文件?然后是否可以从应用程序外部打开和读取该文件?也就是说,应用程序A在它有写入权限的某个地方创建一个文本文件,然后应用程序B从该文件中读取。或者,忘记应用程序B,我能否只是打开并读取它?
由于问题明确要求使用C/C++而不是Obj-C,因此我添加了这个答案,我在这里看到了它,希望对某些人有所帮助:
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);
使用以下 C 代码:
buffer = "/private/var/mobile/Containers/Data/Application/6DA355FB-CA4B-4627-A23C-B1B36980947A/Documents/myfile.txt"
虽然 Obj-C 版本:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
正在返回
documentsDirectory = /var/mobile/Containers/Data/Application/6DA355FB-CA4B-4627-A23C-B1B36980947A/Documents
顺便提一下,如果你注意到了关于“私人”的小差异,我写信给这两个地方,结果他们是相同的。
可以。
使用NSFileHandle
获取对文件的读/写访问权限,使用NSFileManager
创建目录并列出其内容以及进行所有其他类型的文件系统访问。
请记住,每个应用程序都是沙盒化的,并且只能写入其自己指定的目录。您可以使用以下代码获取这些目录的路径:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
然而,您无法访问另一个应用程序的文件。
iTunes会自动备份这些目录,因此如果用户进行设备还原,则会自动恢复它们。同时请注意不要以文件浏览器或“保存对话框”等形式向应用程序用户“公开”文件系统。
printf
语句。 - 341008