首页 > 代码库 > iOS 文件操作

iOS 文件操作


下面整段代码你直接就可以用,具体看看好好看看问题,我也是看别人的。

孰能生巧。

NSString 类,写了几个简单操作调用系统函数。

%@打印NSString, NSArray对象。

%i 整数

%f 浮点


NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSLog(@"path=%@", paths);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    
    NSLog(@"documentsDirectory=%@", documentsDirectory);
    [fileManager changeCurrentDirectoryPath:[documentsDirectory stringByExpandingTildeInPath]];
    [fileManager createFileAtPath:@"fileName" contents:nil attributes:nil];
    [fileManager removeItemAtPath:@"createdNewFile" error:nil];
    
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"fileName"];
    NSLog(@"path=%@", path);
    
    NSString *temp = @"Welcome to blog.csdn.net/qianguozheng";
    int data0 = 800;
    float data1 = 12.34f;
    
    NSMutableData *writer = [[NSMutableData alloc] init];
    
    [writer appendData:[temp dataUsingEncoding:NSUTF8StringEncoding]];
    [writer appendBytes:&data0 length:sizeof(data0)];
    [writer appendBytes:&data1 length:sizeof(data1)];
    [writer writeToFile:path atomically:YES];
    //[writer release];
    
    int gData0;
    float gData1;
    NSString *gData2;
    
    NSData *reader = [NSData dataWithContentsOfFile:path];
    gData2 = [[NSString alloc] initWithData:[reader subdataWithRange:NSMakeRange(0, [temp length])] encoding:NSUTF8StringEncoding];
    
    [reader getBytes:&gData0 range:NSMakeRange([temp length], sizeof(gData0))];
    [reader getBytes:&gData1 range:NSMakeRange([temp length] + sizeof(gData0), sizeof(data1))];
    NSLog(@"gData0:%i gData1:%f gData2:%@", gData0, gData1, gData2);


输出如下:

2015-01-08 22:45:01.423 OC[21613:303] path=(

    "/Users/weeds/Documents"

)

2015-01-08 22:45:01.424 OC[21613:303] documentsDirectory=/Users/weeds/Documents

2015-01-08 22:45:01.429 OC[21613:303] path=/Users/weeds/Documents/fileName

2015-01-08 22:45:01.430 OC[21613:303] gData0:800 gData1:12.340001 gData2:Welcome to blog.csdn.net/qianguozheng



iOS 文件操作