Text file in question is named fp.txt and contains 01, 02, 03, 04, 05, ...10 on each line.
01
02
...
10
Code:
<?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);
?>
So, because of fseek($fp, -1024, SEEK_CUR); is not working properly. What I want is that If Dice == 1, set the file-pointer to previous line i.e. one line up than the current one. But I think negative value is setting the file pointer to end of file, and thus ending the while loop before the actual end of file.
Desired Output is:
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
Note that whenever dice is 2, text is same as previous one. Now it is just stopping at the first occurrence of Dice=1
So basically my question is How to move/relocate file-pointer to previous line?
Please note that dice=rand(1,2) is just for example. In the actual code, $text is a string and if condition is to be true when string does not contain a particular text.
EDIT: Solved, both samples (@hakre 's & mine) are working as desired.
<?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);
?>
This sample is also working as required.
The changes are:
* Addition of "$current = ftell($fp);" after while loop.
* Modification of fseek line in if condition.
* checking for dice==2 instead of dice==1