zoukankan      html  css  js  c++  java
  • writetofile 与 NSFileHandle

     
    [writer writeToFile:logPath atomically:YES];这句是往文件里面写数据  这都是覆盖式写入的

    atomically的YES 或 NO  :YES 表示保证文件的写入原子性,就是说会先创建一个临时文件,直到文件内容写入成功再导入到目标文件里.
                             NO  则直接写入目标文件里.


    如果要采用追加式的文件写入,也就是不覆盖原文件的内容  可以采用NSFileHandle:

     1 #import
     2 int main(int argc, const char * argv[]) 
     3 {
     4     @autoreleasepool {
     5 
     6        NSFileHandle *inFile, *outFile;
     7 
     8        NSData *buffer;
     9 
    10 
    11 
    12         //打开fileA用于读操作
    13 
    14         inFile = [NSFileHandle fileHandleForReadingAtP
    15 
    16         if(inFile == nil)
    17 
    18         {
    19 
    20             NSLog(@"Open of fileA.txt reading failed")
    21 
    22             return 1;
    23 
    24         }
    25 
    26 
    27 
    28        //打开fileB用于更新操作
    29 
    30         outFile = [NSFileHandle fileHandleForWritingAtPath:@"fileB.txt"];
    31 
    32        if(outFile == nil)
    33 
    34        {
    35 
    36            NSLog(@"Open of fileB for writing failed")
    37 
    38            return  2;
    39 
    40        }
    41 
    42 
    43 
    44        //找到并定位到outFile的末尾位置(在此后追加文件)
    45 
    46       [outFile seekToEndOfFile];
    47 
    48 
    49 
    50       //读取inFile并且将其内容写到outFile中
    51 
    52       buffer = [inFile readDataToEndOfFile];
    53 
    54        [outFile writeData:buffer];
    55 
    56  
    57         //关闭读写文件
    58 
    59         [inFile closeFile];
    60 
    61         [outFile closeFile];
    62 
    63      }
    64 
    65     return 0;
    66 
    67  }

     
    在搜索操作执行完毕之后,seekToEndOfFile返回当前文件的偏移量。选择忽略这个值,如果需要,可以使用这个信息来获得程序中文件的大小
  • 相关阅读:
    git 学习笔记
    单选框和复选框的样式修改
    es6常用方法
    js混杂笔记
    Entity Framework 学习第一天
    sublime text2的插件熟悉
    近况
    thinkphp ,进行关联模型的时候出现的问题,版本是3.2
    上传图片的权限问题
    今天学习了下,如何破解wifi
  • 原文地址:https://www.cnblogs.com/song-kl/p/4479108.html
Copyright © 2011-2022 走看看