sykatch
sykatch

Reputation: 301

Script reading from STDIN

I have a php script that reads text files. I use fgetc() to get every character one by one. I open file to read from with fopen(),and then I use file descriptor returned from fopen() as a first argument to fgetc(). I tried to do the same thing with reading from STDIN. I wanted to run the script in a terminal, give it the whole text (that was in a text file before) and press enter. I thought that the script would read it and will run as if it read from a text file, but it doesn't work. It only works when a type every single character alone and press enter after it. Why is that? Is there a possibility to make the script behave the way I wanted? That I can give it the whole text to the terminal at once? Should I use different functions or something?

$inputFile = fopen($path, "w");
while(($char = fgetc($inputFile)) !== false){
    dosomething();
}

What I'm trying to do is to replace $inputFile in fgetc()with STDIN.

Upvotes: 0

Views: 552

Answers (1)

Jan Chimiak
Jan Chimiak

Reputation: 746

See http://php.net/manual/en/features.commandline.io-streams.php, second comment

Note, without the stream_set_blocking() call, fgetcsv() hangs on STDIN, awaiting input from the user, which isn't useful as we're looking for a piped file. If it isn't here already, it isn't going to be.

<?php
stream_set_blocking(STDIN, 0);
$csv_ar = fgetcsv(STDIN);

I think it's the same for fgetc. After all it

string fgetc ( resource $handle ) Gets a character from the given file pointer.

Emphasis mine. See http://php.net/manual/en/function.fgetc.php ...

Upvotes: 1

Related Questions