• NSFileHandle类和NSFileManager,追加数据的操作


    NSFileHandle类主要对文件内容进行读取和写入操作

    NSFileManager类主要对文件的操作(删除、修改、移动、复制等等)

    常用处理方法

     + (id)fileHandleForReadingAtPath:(NSString *)path  打开一个文件准备读取     

     + (id)fileHandleForWritingAtPath:(NSString *)path  打开一个文件准备写入   

     + (id)fileHandleForUpdatingAtPath:(NSString *)path  打开一个文件准备更新  

     -  (NSData *)availableData; 从设备或通道返回可用的数据            

     -  (NSData *)readDataToEndOfFile; 从当前的节点读取到文件的末尾               

     -  (NSData *)readDataOfLength:(NSUInteger)length; 从当前节点开始读取指定的长度数据                           

     -  (void)writeData:(NSData *)data; 写入数据         

     -  (unsigned long long)offsetInFile;  获取当前文件的偏移量            

     -  (void)seekToFileOffset:(unsigned long long)offset; 跳到指定文件的偏移量     

     -  (unsigned long long)seekToEndOfFile; 跳到文件末尾        

     -  (void)truncateFileAtOffset:(unsigned long long)offset; 将文件的长度设为offset字节

     -  (void)closeFile;  关闭文件

     

    /*    向文件添加数据*/

    向文件追加数据

     

    //获取沙盒Documents路径

        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

        NSString *documentDictionary = [paths objectAtIndex:0];

    //创建文件

        NSFileManager *fileManager = [NSFileManager defaultManager];

        NSString *testDictionary = [documentDictionary stringByAppendingPathComponent:@"test"];

        [fileManager createDirectoryAtPath:testDictionary withIntermediateDirectories:YES attributes:nil error:nil];        

     NSString *sourcePath = [testDictionary stringByAppendingPathComponent:@"testfile.text"];                   

    //先写一个空字符进去                         

    NSString *tempStr = @“”;

    [tempStr writeToFile:sourcePath atomically:YES encoding:NSUTF8StringEncoding error:nil];

    //打开这个testfile文件准备更新

    NSFileHandle *fielHandle = [NSFileHandle fileHandleForUpdatingAtPath:sourcePath];                                                        

     [fileHandle seekToEndOfFile];  //将节点跳到文件的末尾          

     NSString *str = @"追加的数据"  ;                

     NSData* stringData  = [str dataUsingEncoding:NSUTF8StringEncoding];          

     [fileHandle writeData:stringData]; 追加写入数据      

     

    //读取数据

    NSData *reader = [NSData dataWithContentsOfFile:_testHeartFilePath];

    NSString *tempStr = [[NSString alloc] initWithData:reader2 encoding:NSUTF8StringEncoding];

     

     [fileHandle closeFile];

  • 相关阅读:
    [组合][DP]luogu P3643 [APIO2016]划艇
    [倍增]luogu P4155 [SCOI2015]国旗计划
    [并查集][线段树]luogu P3273 [SCOI2011]棘手的操作
    pytest警告DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated since Python 3.3,and in 3.9 it will stop working
    docker-compose5分钟搭建wordpress博客网站
    Docker安装入门
    Windows10安装wget命令
    CRC (Cyclic Redundancy Check)
    Linux学习笔记
    Linux学习笔记
  • 原文地址:https://www.cnblogs.com/feng9exe/p/7213684.html
Copyright © 2020-2023  润新知