文件操作
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
NSLog(@"Hello, World!");
//----------- NSFileManager---------//
//实例化一个对象
NSFileManager * f=[NSFileManager defaultManager];
//根据aaa.txt的路径读取内容
NSData *data1=[f contentsAtPath:@"/Users/feifanchengxuyuan/Desktop/aaa.txt"];
NSString *str1=[[NSString alloc]initWithData:data1 encoding:NSUTF8StringEncoding];
NSLog(@"%@",str);
//从一个文件中直接获取数据(不需要转换)
NSLog(@"%@", [NSString stringWithContentsOfFile:@"/Users/feifanchengxuyuan/Desktop/aaa.txt" encoding:NSUTF8StringEncoding error:nil]);
//创建一个b.txt 内容为空
//创建一个bbb.txt 并且把aaa.txt的文件复制到bbb.txt中
[f createFileAtPath:@"/Users/feifanchengxuyuan/Desktop/b.txt" contents:nil attributes:nil];
[f createFileAtPath:@"/Users/feifanchengxuyuan/Desktop/bbb.txt" contents:data1 attributes:nil];
//把str写入到ccc.txt (如果是已经存在该文件,则会覆盖之前的内容)
NSString *[email protected]"zhang";
NSData *data2=[str2 dataUsingEncoding:NSUTF8StringEncoding];
//创建文件
[f createFileAtPath:@"/Users/feifanchengxuyuan/Desktop/ccc.txt" contents:data2 attributes:nil];
//获取路径
NSString *str3= [f currentDirectoryPath];
NSLog(@"%@",str3);
//遍历当前路径
NSArray *array= [f contentsOfDirectoryAtPath:@"/Users/feifanchengxuyuan/Desktop" error:nil];
NSLog(@"%@,array);
// 枚举遍历
NSLog(@"%@:[f enumeratorAtPath:@"/Users/feifanchengxuyuan/Desktop"]);
NSEnumerator *ee=[f enumeratorAtPath:@"/Users/feifanchengxuyuan/Desktop"];
NSArray *array1=[ee allObjects];
NSLog(@"%@,array1);
//深度遍历当前路径
NSArray * array1=[f subpathsAtPath:@"/Users/feifanchengxuyuan/Desktop"];
NSLog(@"%@",array1);
// 创建文件夹 withIntermediateDirectories:YES如果没有该文件,就创建, NO,如果不存就会报错
NSError *error = nil;
[f createDirectoryAtPath:@"/Users/feifanchengxuyuan/Desktop3/aaa1" withIntermediateDirectories:YES attributes:nil error:&error];
if( error )
{
NSLog( @"%@", error );
}
//----------- NSFileHandle--------(重点)-------//
//1 文件必须创建
//2文件必须给出足够的权限 如 chmod 777文件名+文件类型
//获取用户主目录
NSString *homepath = NSHomeDirectory();
NSLog( @"homepath: %@", homepath);
//根据参数连接目录
NSString *sourcepath = [homepath stringByAppendingPathComponent:@"/Desktop/tttt2.txt"];
NSLog( @"sourcepath: %@", sourcepath );
//创建NSFileHandle对象类型fileHandleForUpdatingAtPath 为可更新的类型
//fileHandleForReadingAtPath //读取
NSFileHandle *filhandle = [NSFileHandle fileHandleForUpdatingAtPath:sourcepath];
//定位偏移量到文件内容尾部
[filhandle seekToEndOfFile];
//定义要追加的字符串
NSString *string = @"hello xiaohe sacnkwanc;w\n";
//转化成文件流
NSData *nsdate = [string dataUsingEncoding:NSUTF8StringEncoding];
//写数据
[filhandle writeData:nsdate];
//关闭文件
[filhandle closeFile];
//echo jjjjjj>>aaa.txt 在终端中给aaa.txt添加jjjjjj文本
cat 文件名是读取内容 }
return 0;
}