NSFileSManager:目录文件管理
#import "AppDelegate.h" #define ERROR(a) if(a){NSLog(@"%@",a);exit(-1);} #define PATH @"/Users/huen/Desktop/NSManage" @implementation AppDelegate
NSError *error = nil; NSFileManager *fm = [NSFileManager defaultManager];//单例对象 /* NSArray *arr = [fm contentsOfDirectoryAtPath:PATH error:&error];//浅度遍历目录 ERROR(error);//若上句报错,打印错误,退出程序 NSLog(@"%@",arr); arr = [fm subpathsOfDirectoryAtPath:PATH error:&error];//深度遍历目录 ERROR(error);//若上句报错,打印错误,退出程序 NSLog(@"%@",arr); */ //创建目录 [fm createDirectoryAtPath:[NSString stringWithFormat:@"%@/middle/dir",PATH] withIntermediateDirectories:YES//支持创建middle文件 attributes:nil error:&error]; ERROR(error); //创建文件 [fm createFileAtPath:[NSString stringWithFormat:@"%@/middle/dir/file.rtf",PATH] contents:[@"hello" dataUsingEncoding:NSUTF8StringEncoding] attributes:nil]; ERROR(error); // [fm copyItemAtPath:[NSString stringWithFormat:@"%@/middle/dir/file.rtf",PATH] toPath:[NSString stringWithFormat:@"%@/middle/file.rtf",PATH] error:&error]; ERROR(error); [fm moveItemAtPath:[NSString stringWithFormat:@"%@/middle/dir",PATH] toPath:[NSString stringWithFormat:@"%@/dir",PATH] error:&error]; ERROR(error); //删除 // [fm removeItemAtPath:[NSString stringWithFormat:@"%@/middle/file.rtf",PATH] // error:&error]; // ERROR (error);
NSFileHandle:文件读写操作
//文件写 NSFileHandle *fhw = [NSFileHandle fileHandleForWritingAtPath:@"/Users/huen/Desktop/document.rtf"]; //[fhw truncateFileAtOffset:0];//覆盖写 [fhw seekToEndOfFile];//追加 [fhw writeData:[@"xxx is a good man" dataUsingEncoding:NSUTF8StringEncoding]];
[fhw closeFile]; //文件读 NSFileHandle *fh = [NSFileHandle fileHandleForReadingAtPath:@"/Users/huen/Desktop/document.rtf"]; NSData *data = [fh readDataToEndOfFile]; NSString *s = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@",s);
[fh closeFile];