Objective-c 文件的基本操作

来源:互联网 发布:淘宝 排名 编辑:程序博客网 时间:2024/05/22 08:39

保证testfile文件在程序运行的目录,这个目录与程序编写目录不一致,可以使用NSFileManager实例的currentDirectoryPath查看

#import <Foundation/Foundation.h>int main(int argc, const char * argv[]){    @autoreleasepool {           <span style="white-space:pre"></span>        NSString *fName = @"testfile";        NSFileManager *fm ;        NSDictionary *attr;                //创建文件管理的实例        fm = [NSFileManager defaultManager];                //打印当前目录,这个才是程序运行的目录,        NSLog(@"%@",[fm currentDirectoryPath]);                //文件是否存在        if ([fm fileExistsAtPath:fName] == NO) {            NSLog(@"File doesn't exist!");                 }                //复制文件为 newfile.        if([fm copyItemAtPath:fName toPath:@"newfile" error:NULL]==NO){            NSLog(@"File Copy failed!");               }                // 测试两个文件是否一致        if ([fm contentsEqualAtPath:fName andPath:@"newfile"]==NO){            NSLog(@"File are Not Equal!");                   }                //重命名副本        if ([fm moveItemAtPath:@"newfile" toPath:@"newfile2" error:NULL] ==NO) {            NSLog(@"File rename Failed");        }                //获取文件属性        if ((attr = [fm attributesOfItemAtPath:fName error:NULL]) ==nil) {            NSLog(@"Could't get file attributes!");        }                //打印文件属性中大小        NSLog(@"File size is %llu bytes",[[attr objectForKey:NSFileSize] unsignedLongLongValue]);                        //删除原始文件        if ([fm removeItemAtPath:fName error:NULL] ==NO) {            NSLog(@"File remove failed");        }                        //显示新创建的内容        NSLog(@"%@",[NSString stringWithContentsOfFile:@"newfile2" encoding:NSUTF8StringEncoding error:NULL]);            }    return 0;}
运行结果:

/Users/wudi/Library/Developer/Xcode/DerivedData/prog16.1-eraeaurndadvfjcvyqzecysfsbpx/Build/Products/Debug

File size is 88 bytes

This is a test file with some data in it.

Here's another line of the data.

And a third.



0 0
原创粉丝点击