在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];