1

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.

2 Answers 2

2

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.

0

Use !== to check for FALSE:

while($char != "\n" && $char !== FALSE){
    $char = fgetc($inputFile);
}
2
  • Yes, I tried !== too, but my program starts cycling after it.I have no idea why, because with != it worked fine, it crashed only when it came to 0 character.
    – sykatch
    Mar 12, 2016 at 21:44
  • 1
    I just found out that mistake was somewhere else in the script, !== works fine now, thanks.
    – sykatch
    Mar 13, 2016 at 10:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.