IOS写文件

由于Objective C是C的扩展版,所以,可以直接用C的api来读写文件。

但是,ios本身提供了NSFileManager来进行文件操作

-(void)writeFile:(NSString*)filename:(NSString*)data

{    
//获得应用程序沙盒的Documents目录,官方推荐数据文件保存在此
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);    

NSString* doc_path = [path objectAtIndex:0];    

//NSLog(@"Documents Directory:%@",doc_path);    

//创建文件管理器对象

NSFileManager *fm = [NSFileManager defaultManager];          NSString* _filename = [doc_path stringByAppendingPathComponent:filename];     
//NSString* new_folder = [doc_path stringByAppendingPathComponent:@"test"];    
 //创建目录 
//[fm createDirectoryAtPath:new_folder withIntermediateDirectories:YES attributes:nil error:nil];          
[fm createFileAtPath:_filename contents:[data dataUsingEncoding:NSUTF8StringEncoding] attributes:nil]; 
} 
- (IBAction)sendMailAndWriteFile:(id)sender 
{ //先写入文件 
NSString* _username = username.text; 
NSString* _phone = phone.text ; 
NSString* _email = email.text ; 
NSString* _title = title.text ; 
NSString* filename = @"data.txt"; 
NSString* data = [NSString stringWithFormat:@"用户名:%@\n电话:%@\nEmail:%@\n地址:%@\n*****\n",_username,_phone,_email,_title,nil]; 
[self writeFile:filename:data] ; 
} 

 

 

posted @ 2012-12-22 12:00  ifeixiang  阅读(5327)  评论(0编辑  收藏  举报