Home > Mobile >  Trying to write content to a file I've created, it reads all 3 lines, but when I change the lin
Trying to write content to a file I've created, it reads all 3 lines, but when I change the lin

Time:06-13

$my_content = "This is the first line\n
    This is the second line\n
    This is the third line\n";
    
$my_filename = "save.txt";  

 function file_writer(string $file_to_write, string $content_to_write){
    $file = fopen($file_to_write, "w") or die("Unable to open file");
    file_put_contents($file_to_write, $content_to_write);
    fclose($file);
}
file_writer($my_filename, $my_content);

function file_reader(string $file_to_read, int $num_lines) {
    $file = fopen($file_to_read, "r");
    while(! feof($file))  
    {
        $line = fgets($file);
        echo $line;
    }
}
**file_reader($my_filename, 3);**

CodePudding user response:

Try this:

function file_reader(string $file_to_read, int $num_lines) {
$file = fopen($file_to_read, "r");
$c = 0;
while(! feof($file) && $c != $num_lines)  
{
    $c = $c 1;
    $line = fgets($file);
    echo $line;
    }
}

Your other problem is that you have newlines after newlines.

$my_content = "This is the first line\nThis is the second line\nThis is the third line\n";

CodePudding user response:

function file_reader(string $file_to_read, int $num_lines) {
    $file = fopen($file_to_read, "r");
    $currLineNo = 1;
    while(!feof($file) && (currLineNo < $num_lines))  
    {
        $line = fgets($file);
        echo $line;

        $currLineNo  = 1;
    }
}

Havent tried the code myself. This is roughly way you can stop the loop at arbitrary line number.

  • Related