OC9

it2024-10-24  16

// // main.m // OC9_文件操作 // // Created by zhangxueming on 15/6/19. // Copyright (c) 2015年 zhangxueming. All rights reserved. // #import <Foundation/Foundation.h> int main(int argc, const char * argv[]) { @autoreleasepool { //文件句柄 //以只读的方式创建文件句柄 //+ (instancetype)fileHandleForReadingAtPath:(NSString *)path; //以只写的方式创建文件句柄 //+ (instancetype)fileHandleForWritingAtPath:(NSString *)path; //以可读可写的方式创建文件句柄 NSFileHandle *fh = [NSFileHandle fileHandleForUpdatingAtPath:@"/Users/zhangxueming/Desktop/Test/1.txt"]; //移动文件指针到文件末尾 [fh seekToEndOfFile]; //写文件 NSData *data1 = [@"qianfenghulian" dataUsingEncoding:NSUTF8StringEncoding]; [fh writeData:data1]; NSData *data2 = [@"千锋互联" dataUsingEncoding:NSUTF8StringEncoding]; [fh writeData:data2]; //把文件的内容同步到磁盘中 [fh synchronizeFile]; [fh closeFile];//文件句柄消失的时候, 对应的文件也会关闭; NSFileHandle *fh1 = [NSFileHandle fileHandleForUpdatingAtPath:@"/Users/zhangxueming/Desktop/Test/2.txt"]; //读取文件内容到文件末尾 // NSData *data3 = [fh1 readDataToEndOfFile]; // NSLog(@"data3 = %@", [[NSString alloc] initWithData:data3 encoding:NSUTF8StringEncoding]); //移动文件指针到指定位置 [fh1 seekToFileOffset:6]; //读取文件指定长度大小 NSData *data4 = [fh1 readDataOfLength:9]; NSLog(@"data4 = %@", data4); NSLog(@"data4 = %@", [[NSString alloc] initWithData:data4 encoding:NSUTF8StringEncoding]); //截断文件为指定大小 [fh1 truncateFileAtOffset:30]; } return 0; }

 

转载于:https://www.cnblogs.com/0515offer/p/4589604.html

最新回复(0)