PHP fscanf vs fgets

ε祈祈猫儿з 提交于 2020-01-02 07:34:49

问题


I am able to read an entire string in a line using fgets() but fscanf() is not doing so.

According to PHP manual

fscanf — Parses input from a file according to a format

The function fscanf() is similar to sscanf(), but it takes its input from a file associated with handle and interprets the input according to the specified format, which is described in the documentation for sprintf().

fgets — Gets line from file pointer

Gets a line from file pointer.

Since fscanf() supports formats as mentioned above I can use %s to read an entire line but instead it reads only one word.


回答1:


The PHP documentation of fscanf() and sscanf() is not complete. The formats are similar to the ones used by printf(), but they're not exactly the same. When you're printing, %s will print any string, but when you're scanning it just reads a word. To get more complete information, you need to read the documentation of the C fscanf() function. Some of this information is also in the comments section of the documentation web page.

To read a whole line with fscanf(), use "%[^\\n]". In fscanf(), $[^characters] means to match any sequence of characters that isn't in the set between the brackes (it's similar to [^characters]* in a regular expression). So this matches any sequence of characters other than newline. See http://php.net/manual/en/function.sscanf.php#56076



来源:https://stackoverflow.com/questions/37742699/php-fscanf-vs-fgets

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!