2

如何限制写入文件,如果达到限制则删除最后一行..

例如这里有一个文件:

Line 3
Line 2
Line 1

我只想将它最多排成 3 行.. 所以当我使用任何附加函数写一个新行时,它会删除最后一行.. 假设我刚刚写了一个新行(第 4 行).. 所以它转到最后一行一个并删除它,结果应该是:

Line 4
Line 3
Line 2

对于新的书面行(第 5 行):

Line 5
Line 4
Line 3

数字行不是必需的,如果通过附加函数(file_put_contents / fwrite)有新添加的行,我只想删除最后一行,并将其最大为 3 或我给出的特定数字

4

4 回答 4

3

你可以试试

$max = 3;
$file = "log.txt";
addNew($file, "New Line at : " . time());

使用的功能

function addNew($fileName, $line, $max = 3) {
    // Remove Empty Spaces
    $file = array_filter(array_map("trim", file($fileName)));

    // Make Sure you always have maximum number of lines
    $file = array_slice($file, 0, $max);

    // Remove any extra line 
    count($file) >= $max and array_shift($file);

    // Add new Line
    array_push($file, $line);

    // Save Result
    file_put_contents($fileName, implode(PHP_EOL, array_filter($file)));
}
于 2012-10-22T15:57:16.620 回答
1

这是一种方法:

  1. 用于file()将文件的行读入数组
  2. 用于count()确定数组中的元素是否超过 3 个。如果是这样的话:
    1. 删除数组的最后一个元素array_pop()
    2. 用于array_unshift()将元素(新行)添加到数组的前面
    3. 用数组的行覆盖文件

例子:

$file_name = 'file.txt';

$max_lines = 3;              #maximum number of lines you want the file to have

$new_line = 'Line 4';               #content of the new line to add to the file

$file_lines = file($file_name);     #read the file's lines into an array

#remove elements (lines) from the end of the
#array until there's one less than $max_lines
while(count($file_lines) >= $max_lines) {    
    #remove the last line from the array
    array_pop($file_lines);
}

#add the new line to the front of the array
array_unshift($file_lines, $new_line);

#write the lines to the file
$fp = fopen($file_name, 'w');           #'w' to overwrite the file
fwrite($fp, implode('', $file_lines)); 
fclose($fp); 
于 2012-10-22T15:50:47.197 回答
0

试试这个。

<?php

// load the data and delete the line from the array 

$lines = file('filename.txt'); 
$last = sizeof($lines) - 1 ; 
unset($lines[$last]); 

// write the new data to the file 

$fp = fopen('filename.txt', 'w'); 
fwrite($fp, implode('', $lines)); 
fclose($fp); 

?>
于 2012-10-22T15:55:39.043 回答
0

根据巴巴的回答修改;此代码将在文件开头写入新行,并将擦除最后一行以始终保持 3 行。

<?php
function addNew($fileName, $line, $max) {
    // Remove Empty Spaces
    $file = array_filter(array_map("trim", file($fileName)));

    // Make Sure you always have maximum number of lines
    $file = array_slice($file, 0, --$max);

    // Remove any extra line and adding the new line
    count($file) >= $max and array_unshift($file, $line);

// Save Result
file_put_contents($fileName, implode(PHP_EOL, array_filter($file)));
}

// Number of lines
$max = 3;
// The file must exist with at least 2 lines on it
$file = "log.txt";
addNew($file, "New Line at : " . time(), $max);

?>
于 2016-06-27T15:39:03.393 回答