@fiy-fish
2015-07-19T12:25:08.000000Z
字数 1316
阅读 1369
Objective-c
// main.m
// day08-02-文件内容操作
//
// Created by Aaron on 15/7/10.
// Copyright (c) 2015年 Aaron. All rights reserved.
//
#import <Foundation/Foundation.h>
#if 0
int main(int argc, const char * argv[]) {
@autoreleasepool {
//NSFileHandle
//句柄
//对句柄做操作相当于是在操作文件本身
//读----磁盘转移到内存
//写----内存转移到磁盘
NSFileManager *manager = [NSFileManager defaultManager];
[manager createFileAtPath:@"/users/Aaron/desktop/file1.txt" contents:nil attributes:nil];
//创建文件句柄
NSFileHandle *writeHandle = [NSFileHandle fileHandleForWritingAtPath:@"/users/Aaron/desktop/file1.txt"];
NSString *str = @"helloworld";
//将文件内容转成二进制数据流
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
//重新设置句柄的位置
//注意:句柄是从0开始的
//从第4个字符开始写入
[writeHandle seekToFileOffset:5];
//从文件的最后一个字符开始写入
//[writeHandle seekToEndOfFile];
//正式写入
[writeHandle writeData:data];
//同步磁盘
[writeHandle synchronizeFile];
//关闭文件
[writeHandle closeFile];
}
return 0;
}
#endif
int main()
{
//读文件
NSFileHandle *readHandle = [NSFileHandle fileHandleForReadingAtPath:@"/users/qianfeng/desktop/file.txt"];
//取出文件中4个字符(从头开始取)
NSData *data = [readHandle readDataOfLength:4];
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",str);
//从第二个字符开始取
[readHandle seekToFileOffset:2];
//取字符的长度是2
data = [readHandle readDataOfLength:2];
str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",str);
[readHandle closeFile];
}