sykatch
sykatch

Reputation: 301

How to correctly read file to EOF

I have a function that reads comments in a text file. Comment can last to end of line, if there is no end of line it lasts to end of file. My problem is I can't find out how to test it whether the end of file was reached. At first I had this:

while($char != "\n" && $char != false){
    $char = fgetc($inputFile);
}

If there was 0 in a comment it ended the loop which I didn't want to. Then I tried this:

while($char != "\n" && !feof($inputFile)){ 
    $char = fgetc($inputFile);
}

This broke up the whole program. I tried to google something but feof and != false is all I found.

Upvotes: 1

Views: 3204

Answers (2)

Shashank Shah
Shashank Shah

Reputation: 2167

Instead you can read your file until it reach end of line!

You can try feof function to check the end of file.

//Output a line of the file until the end is reached
while(!feof($file) {
    echo fgets($file) . "<br />";
}
fclose($file);

For fgets function if you do not specify the length then it will keep reading from the stream until it reaches the end of the line.

Upvotes: 2

Bart Friederichs
Bart Friederichs

Reputation: 33531

Use !== to check for FALSE:

while($char != "\n" && $char !== FALSE){
    $char = fgetc($inputFile);
}

Upvotes: 0

Related Questions