PHP fscanf与fgets

问题描述:

我可以使用fgets()读取一行中的整个字符串,但是fscanf()不能这样做.

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

根据PHP手册

fscanf —根据格式分析文件中的输入

fscanf — Parses input from a file according to a format

函数fscanf()sscanf()类似,但是它从与handle相关联的文件中获取输入,并根据指定的格式解释输入,这在sprintf()的文档中进行了介绍.

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 —从文件指针获取行

fgets — Gets line from file pointer

从文件指针获取一行.

由于fscanf()支持上述格式,因此我可以使用%s读取整行,但只能读取一个单词.

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

fscanf()sscanf()的PHP文档不完整.格式与printf()使用的格式相似,但并不完全相同.在打印时,%s将打印任何字符串,但是在扫描时,它只会读取一个单词.要获取更完整的信息,您需要阅读C fscanf()函数的文档.其中一些信息也位于文档网页的注释部分.

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.

要使用fscanf()读取整行,请使用"%[^\\n]".在fscanf()中,$[^characters]表示匹配括号之间不在集合中的任何字符序列(与正则表达式中的[^characters]*相似).因此,它匹配换行符以外的任何字符序列.参见 http://php.net/manual/zh/function.sscanf.php# 56076

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