文件的基本操作( NSFileManager)


文件或目录是使用文件的路径名唯一标识,每个路径名都是一个NSString对象。

路径名分为相对路径名和完整路径名:

相对路径名是相当于当前目录的路径名。以Student类为例,文件名Student.m意味着当前目录中的文件Student.m。

完整路径名也称绝对路径名,以斜线/开始,每个斜线实际上就是一个目录,第一个斜线就是根目录。

特殊字符(~):~computer表示用户computer的主目录的缩写,它可能是/User/computer。

常见NSFileManager文件方法:

复制文件:(to不能是已存在的)

-  (BOOL)copyPath:(NSString *)srctoPath:(NSString *)dest handler:(id)handler

重命名或者移动一个文件:(to可能是已存在的)

-  (BOOL)movePath:(NSString *)srctoPath:(NSString *)dest handler:(id)handler

删除一个文件:

-  (BOOL)removeFileAtPath:(NSString*)path handler:(id)handler

测试文件是否存在:

-  (BOOL)fileExistsAtPath:(NSString *)path;

测试文件是否存在,并且能否执行读操作

- (BOOL)isReadableFileAtPath:(NSString *)path;

测试文件是否存在,并且能否执行写操作

  - (BOOL)isWritableFileAtPath:(NSString*)path;

从文件中读取数据:

  - (NSData *)contentsAtPath:(NSString*)path;

向文件中写入数据:

-  (BOOL)createFileAtPath:(NSString *)path contents:(NSData *)data attributes:(NSDictionary *)attr;

获取文件属性:

-(NSDictionary*)

更改文件属性:

-  (BOOL)changeFileAttributes:(NSDictionary*)attributes atPath:(NSString *)path


简单的创建,读文件例子:

#import<Foundation/Foundation.h>

 

int main(int argc, const char * argv[])

{

 

    @autoreleasepool {

        NSString *fname=@"testfile.txt";

        NSString *text=@"I am a student";

        NSFileManager *fm;

        NSData *data=[text dataUsingEncoding:NSUTF8StringEncoding];

       fm=[NSFileManager defaultManager];

        [[NSFileManager defaultManager]createFileAtPath:fname contents:nil attributes:nil];        //如果没有文件,创建一个是必须的

        if ([fm fileExistsAtPath:fname]==NO) {

            NSLog(@"文件没有生成");

           

            exit(1);

        }

    BOOL isOk=[fm createFileAtPath:fname contents:data attributes:nil];

    if (isOk) {

        NSLog(@"文件创建成功");

    }else{

        NSLog(@"失败");

    }

        NSLog(@"%@",[NSString stringWithContentsOfFile:fname encoding:NSUTF8StringEncoding error:nil]);

    }

    return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值