http://blog.csdn.net/pipisorry/article/details/37073843
安全
sscanf/scanf正则使用方法app
%[ ] 的使用方法:%[ ]表示要读入一个字符集合, 假设[ 后面第一个字符是”^”,则表示反意思。函数
[ ]内的字符串可以是1或不少其它字符组成。post
空字符集(%[])是违反规则的。可spa
致使不可预知的结果。%[^]也是违反规则的。
.net
%[a-z] 读取在 a-z 之间的字符串,假设不在此以前则中止。如orm
char s[]="hello, my friend” ; // 注意: ,逗号在不 a-z之间blog
sscanf( s, “%[a-z]”, string ) ; // string=hello
ip
%[^a-z] 读取不在 a-z 之间的字符串。假设碰到a-z之间的字符则中止,如字符串
char s[]="HELLOkitty” ; // 注意: ,逗号在不 a-z之间
sscanf( s, “%[^a-z]”, string ) ; // string=HELLO
%*[^=] 前面带 * 号表示不保存变量。跳过符合条件的字符串。
char s[]="notepad=1.0.0.1001" ;
char szfilename [32] = "" ;
int i = sscanf( s, "%*[^=]", szfilename ) ; // szfilename=NULL,因为没保存
int i = sscanf( s, "%*[^=]=%s", szfilename ) ; // szfilename=1.0.0.1001
%40c 读取40个字符
The run-time library does not automatically append a null terminator to the string, nor does reading 40 characters automatically terminate the scanf() function. Because the library uses buffered input, you must press the ENTER key to terminate the string scan. If you press the ENTER before the scanf() reads 40 characters, it is displayed normally。 and the library continues to prompt for additional input until it reads 40 characters
%[^=] 读取字符串直到碰到’=’号。’^’后面可以带不少其它字符,如:
char s[]="notepad=1.0.0.1001" ;
char szfilename [32] = "" ;
int i = sscanf( s, "%[^=]", szfilename ) ; // szfilename=notepad
假设參数格式是:%[^=:] ,那么也可以从 notepad:1.0.0.1001读取notepad
使用样例:
char s[]="notepad=1.0.0.1001" ;
char szname [32] = "" ;
char szver [32] = “” ;
sscanf( s, "%[^=]=%s", szname , szver ) ; // szname=notepad, szver=1.0.0.1001
总结:%[]有很是大的功能,但是并不是非常常常使用到,主要因为:
一、不少系统的 scanf 函数都有漏洞. (典型的就是 TC 在输入浮点型时有时会出错).
二、使用方法复杂, easy出错.
三、编译器做语法分析时会很是困难, 从而影响目标代码的质量和运行效率.
我的认为第3点最致命,越复杂的功能每每运行效率越低下。而一些简单的字符串分析咱们可以自已处理。
一、 * 亦可用于格式中, (即 %*d 和 %*s) 加了星号 (*) 表示跳过此数据不读入. (也就是不把此数据读入參数中)
二、{a|b|c}表示a,b,c中选一。[d],表示可以有d也可以没有d。
三、width表示读取宽度。
四、{h | l | I64 | L}:參数的size,一般h表示单字节size。I表示2字节 size,L表示4字节size(double例外),l64表示8字节size。
五、type : 就是%s,%d之类。
六、特别的:%*[width] [{h | l | I64 | L}]type 表示知足该条件的被过滤掉,不会向目标參数中写入值
假设达到文件末尾。则返回EOF,当错误发生的时候也将返回EOF。你可以经过输出errno来查看错误代码。
假设使用fscanf来推断文件是否结束,将会存在安全隐患,假设每次读取的时候都是匹配失败,那么返回值永远都不会是EOF。
scanf族的函数都是要先将数据读入缓冲区。而后在冲缓冲里读取。
注意:scanf族函数会忽略一行開始的空白
from:http://blog.csdn.net/pipisorry/article/details/37073843