5

I have always used readline in my console commands before, but today I've come across the fread and fgets functions and my question is: what is the difference in using these two approaches:

// first
$inputLine = readline();

// second
$inputLine = fgets(STDIN);

they both do pretty much the same, do they not?

hvertous
  • 1,133
  • 11
  • 25
  • Huh, I'm so not familiar with `readline()` in php ... I've only ever used `fgets()` ;) You could write up a benchmark test, and see if theres really any big difference. Otherwise, it may end up being just which you prefer. – IncredibleHat Dec 19 '17 at 20:24
  • 1
    the file pointer makes the difference, but i am not really familiar with them right now, more info: http://php.net/manual/en/function.fgets.php http://php.net/manual/en/function.readline.php – Honsa Stunna Dec 19 '17 at 20:29

4 Answers4

1

readline() reads input from STDIN by default, while fgets() reads from any resource. Also, readline() takes more time to execute than fgets()

bansari
  • 11
  • 1
  • 2
0

fgets is far faster then the readline. I don't exactly know why, nevertheles I can give you a bit of benchmarking.

I often participate solving problems on codeforces.com. On one of the problem I had time limit issue(when solving with PHP), I was using readline and the time for solution was more than 2 sec. After I replace readline-s with fgets the solving time was 400ms.

So fgets is pretty fast.

giunashvili
  • 76
  • 1
  • 4
0

From the readline docs:

The readline functions implement an interface to the GNU Readline library. These are functions that provide editable command lines. An example being the way Bash allows you to use the arrow keys to insert characters or scroll through command history.

readline takes a single argument which is the $prompt string and it also trims the newline for you. Additionally, the extension functions feature a command history like bash which could allow you to use arrow keys to scroll through previous entries, the ability to do completion and more. As others habve noted in previous answers, the additional functionality does add a bit of overhead so could be slower.

fgets is a bit more basic and simply gets input from a file pointer.

-1

The only possible difference I can think of is just that readline() takes no arguments and can only read input from STDIN by default, whilst fgets() can take any resource to read from. So, in other words readline() is a synonym to fgets with the first predefined argument, like, for instance, fprintf() and printf().

Consider the following:

fprintf(STDOUT, "hello!");
printf("hello!);

This is quite common in php standard library.

hvertous
  • 1,133
  • 11
  • 25