最近在写运维开发时,常常遇见一些常见的文件的文件操做。
特别在处理高并发的需求时,须要REDIS DOCUMENT DB同时操做,若是业务人员在文件处理上花费太多的时间会下降开发效率,所以笔者把本身在开发中常常用的几个函数贴出来,提供给你们复制粘贴。若是代码上有什么问题,也但愿你们提出来。php
w : Open for reading and writing; place the file pointer at the beginning of the file truncate the file to zero length.
a : Open for reading and writing; place the file pointer at the end of the file.数据库
function inputStrToFile($filename, $writetext, $openmod = 'w'){ $fp = fopen($filename, $openmod); if ($fp) { flock($fp, 2); fwrite($fp, $writetext); fclose($fp); return true; } else { return false; } }
function getFileToStr($fileName) { $buffer = ''; if (!file_exists($fileName)) { throw new Exception('文件不存在', 0); } $handle = fopen("./star_star_academy_set_10.txt", "r"); while (!feof($handle)) { $buffer = $buffer . fgets($handle); } fclose($handle); return $buffer; }
function getJsonFileToArr($fileName) { if (!file_exists($fileName)) { throw new Exception('文件不存在', 0); } //Open for reading only; place the file pointer at the beginning of the file $file = fopen($fileName, 'r'); $filestr = fread($file, filesize($fileName)); fclose($file); return json_decode($filestr, 'true'); }
function getDbToJsonFile($tableName, $fileName) { //数据库操做 $data = $this->db->select($tableName, '*'); $filestr = json_encode($data); //Open for reading and writing; place the file pointer at the beginning of the file //truncate the file to zero length. $file = fopen($this->filePath . $fileName, 'w'); fwrite($file, $filestr); fclose($file); }
function inputArrToFile($filename, $array, $valueName) { $cachefile = $filename; $cachetext = "<?php\r\n" . '$' . $valueName . '=' . var_export($array, true) . ';'; return inputStrToFile($cachefile, $cachetext, 'w'); }
调用时只须要把文件包含进来就能够json