php 中的 readline 与 fread/fgets 之间的区别
Difference between readline vs fread/fgets in php
我之前一直在我的控制台命令中使用 readline
,但今天我遇到了 fread
和 fgets
函数,我的问题是:有什么区别使用这两种方法:
// first
$inputLine = readline();
// second
$inputLine = fgets(STDIN);
他们做的几乎一样,不是吗?
我能想到的唯一可能的区别就是 readline()
没有参数,默认情况下只能读取来自 STDIN
的输入,而 fgets()
可以接受任何 [=14] =] 阅读。因此,换句话说,readline()
是带有第一个预定义参数的 fgets
的同义词,例如 fprintf()
和 printf()
.
考虑以下因素:
fprintf(STDOUT, "hello!");
printf("hello!);
这在 php 标准库中很常见。
readline() 默认从 STDIN 读取输入,而 fgets() 从任何资源读取。此外,readline() 比 fgets()
需要更多的执行时间
fgets 比 readline 快得多。我不知道为什么,不过我可以给你一些基准测试。
我经常在 codeforces.com 上参与解决问题。在其中一个我有时间限制的问题上(当用 PHP 解决时),我正在使用 readline 并且解决的时间超过 2 秒。我用 fgets 替换 readline-s 后,求解时间为 400ms。
所以 fgets 非常快。
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
接受一个参数,即 $prompt
字符串,它还会为您修剪换行符。此外,扩展功能还具有命令历史记录,例如 bash,它可以让您使用箭头键滚动浏览以前的条目、完成功能等等。正如其他人在之前的回答中指出的那样,附加功能确实会增加一些开销,因此速度可能会变慢。
fgets
更基本一些,只是从文件指针获取输入。
我之前一直在我的控制台命令中使用 readline
,但今天我遇到了 fread
和 fgets
函数,我的问题是:有什么区别使用这两种方法:
// first
$inputLine = readline();
// second
$inputLine = fgets(STDIN);
他们做的几乎一样,不是吗?
我能想到的唯一可能的区别就是 readline()
没有参数,默认情况下只能读取来自 STDIN
的输入,而 fgets()
可以接受任何 [=14] =] 阅读。因此,换句话说,readline()
是带有第一个预定义参数的 fgets
的同义词,例如 fprintf()
和 printf()
.
考虑以下因素:
fprintf(STDOUT, "hello!");
printf("hello!);
这在 php 标准库中很常见。
readline() 默认从 STDIN 读取输入,而 fgets() 从任何资源读取。此外,readline() 比 fgets()
需要更多的执行时间fgets 比 readline 快得多。我不知道为什么,不过我可以给你一些基准测试。
我经常在 codeforces.com 上参与解决问题。在其中一个我有时间限制的问题上(当用 PHP 解决时),我正在使用 readline 并且解决的时间超过 2 秒。我用 fgets 替换 readline-s 后,求解时间为 400ms。
所以 fgets 非常快。
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
接受一个参数,即 $prompt
字符串,它还会为您修剪换行符。此外,扩展功能还具有命令历史记录,例如 bash,它可以让您使用箭头键滚动浏览以前的条目、完成功能等等。正如其他人在之前的回答中指出的那样,附加功能确实会增加一些开销,因此速度可能会变慢。
fgets
更基本一些,只是从文件指针获取输入。