文件操作

#import <Foundation/Foundation.h>
#define file_Path   @"/Users/vincent/Desktop/hello.txt"
void readFile()
{
//创建一个读取文件内容的handle
NSFileHandle *handle_read = [NSFileHandle fileHandleForReadingAtPath:file_Path];

//读取文件到末尾)返回的就是读取到的数据(
NSData *data_read = [handle_read readDataToEndOfFile];

//将获取到的数据转成字符串(编码格式使用UTF-8)
NSString *string_read=[[NSString alloc]initWithData:data_read encoding:NSUTF8StringEncoding];

NSLog(@"%@",string_read);
}

void readFileOfLength()
{
    //创建一个读取文件内容的handle
    NSFileHandle *handle_read = [NSFileHandle fileHandleForReadingAtPath:file_Path];
   
    //返回文件中有效数据的时候,会跳到文件末尾
    NSInteger length = [handle_read availableData].length;
   
    NSLog(@"%ld",length);
   
    //        跳转到文件开头
    [handle_read seekToFileOffset:0];
   
    //读取文件到末尾)返回的就是读取到的数据(
    NSData *data_read = [handle_read readDataOfLength:length/2];
   
    //将获取到的数据转成字符串(编码格式使用UTF-8)
    NSString *string_read=[[NSString alloc]initWithData:data_read encoding:NSUTF8StringEncoding];
   
    NSLog(@"%@",string_read);
}

void writeFile()
{
    //写文件(指定写到哪个文件)
        NSFileHandle *handle_write=[NSFileHandle fileHandleForWritingAtPath:file_Path];
       
        //写文件
        NSString *string_w=@" 玻璃上有雾气";
       
        NSData *data_w=[string_w dataUsingEncoding:NSUTF8StringEncoding];//字符串转换成data数据
       
       
       
       
//        写到那个文件
     
       
       
       
       
//        写到指定位置....文件末尾
       
          [handle_write seekToEndOfFile];
//        开始写入数据
        [handle_write writeData:data_w];
       

}

int main(int argc, const char * argv[]) {
    @autoreleasepool {
  
        //2015年11月3日
       
        NSDateFormatter *dateForMatter=[[NSDateFormatter alloc]init];
        [dateForMatter setAMSymbol:@"AM"];
        [dateForMatter setPMSymbol:@"PM"];
        [dateForMatter setDateFormat:@"YYYY年MM月dd日  hh:mm:ss EEE aaa"];
       
        NSString *date_s=[dateForMatter stringFromDate:[NSDate date]];
       
        date_s = [NSString stringWithFormat:@"%@ ",date_s];//换行
        NSLog(@"%@",date_s);
       
       
        NSData *data_w=[date_s dataUsingEncoding:NSUTF8StringEncoding];
        NSFileHandle *handle_w=[NSFileHandle fileHandleForWritingAtPath:file_Path];
       
        [handle_w seekToFileOffset:0];   //写入开头位置
        [handle_w writeData:data_w];     //写入
       
       
       
       
       
    }
    return 0;
}
原文地址:https://www.cnblogs.com/shuxiachahu123/p/4934070.html