2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > object-c中管理文件和目录:NSFileManager使用方法

object-c中管理文件和目录:NSFileManager使用方法

时间:2023-10-12 14:56:48

相关推荐

object-c中管理文件和目录:NSFileManager使用方法

object-c中管理文件和目录:NSFileManager使用方法

对于NSFileManager,文件或目录是使用文件的路径名唯一标识的。每一个路径名都是一个NSString对象,它可以是相对路径名,也可以是完整路径名。

相对路径名是相对于当前目录的路径名。所以,文件名file.m意味着当前目录中的file.m。斜线字符用于隔开路径中的目录列表。

完整路径名,也称绝对路径名,以斜线“/”开头,斜线实际上就是一个目录,称为 根目录。

这个特殊字符(~)用作用户主目录的缩写。点“ . ”表示当前目录,两点“ .. ”表示父目录

下面是常见的NSFileManager文件方法:

下面是一些基本的文件操作的代码示例:

[plain]view plaincopyprint? #import<Foundation/Foundation.h>intmain(intargc,constchar*argv[]){@autoreleasepool{NSString*fName=@"testfile.txt";NSFileManager*fm;NSDictionary*attr;//创建文件管理对象fm=[NSFileManagerdefaultManager];//判断文件是否存在if([fmfileExistsAtPath:fName]==NO){NSLog(@"Filedoesn'texist!");return1;}//将testfile.txt文件拷贝出一个新的文件newfile.txtif([fmcopyPath:fNametoPath:@"newfile.txt"handler:nil]==NO){NSLog(@"Filecopyfailed!");return2;}//判断两个文件内容是否相等if([fmcontentsEqualAtPath:fNameandPath:@"newfile.txt"]==NO){NSLog(@"Filearenotequal!");return3;}//将文件newfile.txt重命名为newfile2.txtif([fmmovePath:@"newfile.txt"toPath:@"newfile2.txt"handler:nil]==NO){NSLog(@"Filerenamefailed!");return4;}//获取文件newfile2.txt的大小,并输出if((attr=[fmfileAttributesAtPath:@"newfile2.txt"traverseLink:NO])==nil){NSLog(@"Couldn'tgetfileattributes!");return5;}NSLog(@"Filesizeis%ibytes",[[attrobjectForKey:NSFileSize]intValue]);//移出原始文件testfile.txtif([fmremoveFileAtPath:fNamehandler:nil]==NO){NSLog(@"Fileremovalfailed!");return6;}NSLog(@"Alloperationsweresuccessful!");//输出文件内容NSLog(@"%@",[NSStringstringWithContentsOfFile:@"newfile2.txt"encoding:NSUTF8StringEncodingerror:nil]);}return0;}

#import <Foundation/Foundation.h>int main(int argc, const char * argv[]){@autoreleasepool {NSString *fName = @"testfile.txt";NSFileManager *fm ;NSDictionary * attr;//创建文件管理对象fm = [NSFileManager defaultManager];//判断文件是否存在if([fm fileExistsAtPath:fName] == NO){NSLog(@"File doesn't exist!");return 1;}//将 testfile.txt 文件拷贝出一个新的文件 newfile.txtif([fm copyPath:fName toPath:@"newfile.txt" handler:nil] == NO){NSLog(@"File copy failed!");return 2;}//判断两个文件内容是否相等if([fm contentsEqualAtPath:fName andPath:@"newfile.txt"] == NO){NSLog(@"File are not equal!");return 3;}//将文件 newfile.txt 重命名为 newfile2.txtif([fm movePath:@"newfile.txt" toPath:@"newfile2.txt" handler:nil] == NO){NSLog(@"File rename failed!");return 4;}//获取文件 newfile2.txt 的大小,并输出if((attr = [fm fileAttributesAtPath:@"newfile2.txt" traverseLink:NO]) == nil){NSLog(@"Couldn't get file attributes!");return 5;}NSLog(@"File size is %i bytes",[[attr objectForKey:NSFileSize] intValue]);//移出原始文件testfile.txtif([fm removeFileAtPath:fName handler:nil] == NO){NSLog(@"File removal failed!");return 6;}NSLog(@"All operations were successful!");//输出文件内容NSLog(@"%@",[NSString stringWithContentsOfFile:@"newfile2.txt" encoding:NSUTF8StringEncoding error:nil]);}return 0;}

posted on -03-09 00:13 江宇旋 阅读(...) 评论(...) 编辑 收藏

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。