iOS在文件末尾写入内容

来源:互联网 发布:航信数据维护 编辑:程序博客网 时间:2024/05/29 21:16

-(NSString*)infoFilePath

{

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

   NSString *MyDocpath=[Paths objectAtIndex:0];

    NSString *filename=[MyDocpathstringByAppendingPathComponent:[NSStringstringWithFormat:@"infoFile"]];

    

   return filename;

}


-(NSString *)currentTime{

   NSDate *currentDate = [NSDatedate];

    NSDateFormatter *dateformatter=[[NSDateFormatteralloc] init];

    [dateformattersetDateFormat:@"YYYY-MM-dd mm:ss"];

   NSString *currentString=[dateformatter stringFromDate:currentDate];

   return currentString;

}


-(void)allWriteToFileWithLocalMac:(NSString *)localMac andRemoteMac:(NSString *)remoteMac andLength:(int)length{

    

   NSData *buffer;

    

    if (![[NSFileManagerdefaultManager] fileExistsAtPath:[selfinfoFilePath]]) {

        

        NSLog(@"%@",@"文件不存在");

       NSString *s = [NSStringstringWithFormat:@"开始了:\r"];

        [s writeToFile:[selfinfoFilePath]atomically:YESencoding:NSUTF8StringEncodingerror:nil];

        

    }

    

   NSString *filePath = [selfinfoFilePath];

    

   NSFileHandle  *outFile = [NSFileHandlefileHandleForWritingAtPath:filePath];

    

   if(outFile == nil)

    {

        NSLog(@"Open of file for writing failed");

    }

    

    //找到并定位到outFile的末尾位置(在此后追加文件)

    [outFileseekToEndOfFile];

    

    //读取inFile并且将其内容写到outFile

    NSString *bs = [NSStringstringWithFormat:@"发送数据时间:%@--localMac:%@--remoteMac:%@--length:%d \n",[selfcurrentTime],localMac,remoteMac,length];

    buffer = [bs dataUsingEncoding:NSUTF8StringEncoding];

    

    [outFilewriteData:buffer];

    

    //关闭读写文件  

    [outFilecloseFile];

}



        //测试写入文件

        [selfallWriteToFileWithLocalMac:LocalMac andRemoteMac:RemoteMac andLength:(int)[[NSDatadataWithBytes:local_onoff_msg length:128] length]];


0 0
原创粉丝点击