ios沙盒轻量文件操作(可以使用fopen)

xiaoxiao2021-02-28  27

ios开发的一些文件操作

在ios开发中,我们不可避免地要进行文件操作,对于一些轻量需求,用自带API的文件操作略有不足,SQLite又有点大材小用,因此可以在需要的地方自己用fopen一类的c语言文件指针操作进行文件读写,自由度也较大(在沙盒目录内)。

使用自带API时,像读取一个长度未知的字符串这种很简单的操作,我由于iOS开发水平有限,不知道该用什么API,但是c语言的函数很熟悉,所以可以结合c语言的文件操作。我个人的原则是,什么方便,什么效率高,就用什么方法,管他是c标准库,还是苹果官方框架,还是开源框架,只要能够起到作用,且不违反法律,就能用。

创建文件

示例代码

- (void)createFile{ //显示沙盒目录 NSString *homePath = NSHomeDirectory(); NSLog(@"Home Path is %@", homePath); NSArray *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //获取Documents目录 NSString *documentsPath = [docPath objectAtIndex:0]; NSLog(@"Document Path is %@", documentsPath); //文件1,使用c标准库进行创建 NSString *NSfilePath = [documentsPath stringByAppendingPathComponent:@"鸿雁自南人自北.data"]; const char *filePath = [NSfilePath cStringUsingEncoding:NSUTF8StringEncoding]; FILE *fp = fopen(filePath, "w"); if(fp == NULL) { NSLog(@"文件打开错误"); } else { NSLog(@"沙盒内打开成功"); NSString *NSText = @"鸿雁自南 人自北"; const char *text_str = [NSText UTF8String]; //fwrite(text_str, sizeof(char), strlen(text_str), fp); fprintf(fp, "%s", text_str); fclose(fp); fp = NULL; } //文件2, 使用iOS API进行创建 NSString *NSfilePath2 = [documentsPath stringByAppendingPathComponent:@"人自北.data"]; NSFileManager *fileManager = [NSFileManager defaultManager]; [fileManager createFileAtPath:NSfilePath2 contents:nil attributes:nil];

列出Documents文件夹下的文件(使用iOS API)

-(void)listFiles{ NSArray *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSLog(@"docPath: %@", docPath); NSString *documentPath = [docPath objectAtIndex:0]; NSFileManager *fileManager = [NSFileManager defaultManager]; NSArray *files = [fileManager subpathsAtPath:documentPath]; for(int i = 0; i < files.count; ++i) { NSString *filename = files[i]; NSLog(@"NO.%d filename is %@", i, filename); } }

读取文件(使用标准c库)

-(void)showFile{ NSArray *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentPath = [docPath objectAtIndex:0]; NSString *NSfilePath = [documentPath stringByAppendingPathComponent:@"鸿雁自南人自北.data"]; const char *filePath = [NSfilePath UTF8String]; FILE *fp = fopen(filePath, "r"); char read_buffer[256] = {0}; if(fp == NULL) { NSLog(@"文件读取错误"); } else { //fscanf(fp, "%s", read_buffer); fgets(read_buffer, sizeof(read_buffer), fp); NSString *tempNSString = [NSString stringWithUTF8String:read_buffer]; NSLog(@"文件内容: %@", tempNSString); } }
转载请注明原文地址: https://www.6miu.com/read-2630786.html

最新回复(0)