有问题的文本文件名为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);工作不正常。我想要的是如果Dice == 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是一个字符串,如果string不包含特定文本,则条件为true。
编辑: 解决了,两个样本(@hakre和我的)正在按预期工作。
答案 0 :(得分:4)
你从文件中读出一行,但只有当骰子不是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();
}
}
答案 1 :(得分:1)
<?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