提问人:DavChana 提问时间:6/11/2012 最后编辑:DavChana 更新时间:7/4/2012 访问量:4639
如何在php中将文件指针移动到上一行?
How to move file pointer to previous line in php?
问:
有问题的文本文件名为 fp.txt,包含 01、02、03、04、05、...每行 10 个。
01
02
...
10
法典:
<?php
//test file for testing fseek etc
$file = "fp.txt";
$fp = fopen($file, "r+") or die("Couldn't open ".$file);
$count = 0;
while(!(feof($fp))){ // till the end of file
$text = fgets($fp, 1024);
$count++;
$dice = rand(1,2); // just to make/alter the if condition randomly
echo "Dice=".$dice." Count=".$count." Text=".$text."<br />";
if ($dice == 1){
fseek($fp, -1024, SEEK_CUR);
}
}
fclose($fp);
?>
所以,因为 fseek($fp, -1024, SEEK_CUR);工作不正常。我想要的是,如果骰子==1,将文件指针设置为上一行,即比当前行多一行。但我认为负值是将文件指针设置为文件末尾,从而在文件实际结束之前结束 while 循环。
所需输出为:
Dice=2 Count=1 Text=01
Dice=2 Count=2 Text=02
Dice=2 Count=3 Text=03
Dice=1 Count=4 Text=03
Dice=2 Count=5 Text=04
Dice=2 Count=6 Text=05
Dice=2 Count=7 Text=06
Dice=1 Count=8 Text=06
Dice=1 Count=9 Text=06
Dice=2 Count=10 Text=07
.... //and so on until Text is 10 (Last Line)
Dice=2 Count=n Text=10
请注意,每当骰子为 2 时,文本与前一个相同。现在它只是在第一次出现 Dice=1 时停止
所以基本上我的问题是:如何移动/重新定位文件指针到上一行?
请注意,dice=rand(1,2) 只是示例。在实际代码中,$text 是一个字符串,当字符串不包含特定文本时,如果条件为 true。
编辑: 解决了,两个样本(@hakre的和我的)都按预期工作。
答:
4赞
hakre
6/11/2012
#1
您从文件中读出一行,但仅当骰子不是 1 时才转发到下一行。
考虑为此使用 SplFileObject
,它提供了一个更适合你的方案的接口,我会说:
$file = new SplFileObject("fp.txt");
$count = 0;
$file->rewind();
while ($file->valid())
{
$count++;
$text = $file->current();
$dice = rand(1,2); // just to make alter the if condition randomly
echo "Dice=".$dice." Count=".$count." Text=".$text."<br />";
if ($dice != 1)
{
$file->next();
}
}
评论
0赞
DavChana
6/11/2012
谢谢,按要求工作。我还发现,按照我的回答中的解释进行以下修改可以使其按要求工作。
1赞
hakre
6/11/2012
啊,现在看到你加了一个答案。
1赞
DavChana
6/11/2012
#2
<?php
$file = "fp.txt";
$fp = fopen($file, "r+") or die("Couldn't open ".$file);
$eof = FALSE; //end of file status
$count = 0;
while(!(feof($fp))){ // till the end of file
$current = ftell($fp);
$text = fgets($fp, 1024);
$count++;
$dice = rand(1,2); // just to alter the if condition randomly
if ($dice == 2){
fseek($fp, $current, SEEK_SET);
}
echo "Dice=".$dice." Count=".$count." Text=".$text."<br />";
}
fclose($fp);
?>
此示例也按要求工作。
这些变化是:
* Addition of "$current = ftell($fp);" after while loop.
* Modification of fseek line in if condition.
* checking for dice==2 instead of dice==1
评论
file()
将文件转换为数组并操作数组,会更容易。