作者scwg (喂~~~~~~~)
看板b92902xxx
标题Re: [问题] `gets' function is dangerous and sh …
时间Thu Nov 20 20:37:10 2003
※ 引述《beagle1 (满城飞絮风吹雪)》之铭言:
: 所以改用 fgets 来取代 gets 几乎已经成为惯例了...
: 用法其实差不多, 以你的程式可以把 gets(line) != NULL 改成这样:
: fgets(line, SIZE*5, stdin) != NULL
: 效果完全一样, 只差在 input line 过长 (超过 size) 的时候会被截断,
: 避免 segmentation fault 之类的悲惨结果...
: 此外...
: 我用 fgets 之後, 还会习惯在最後一个 char 填 '\0';
: 因为呢, 万一真的过长被截断, 这个 char array 是没有字串结束记号的,
: 所以接下来如果用 strlen() 之类的 function 去处理, 有可能跑不完...
: 所以动手处理字串之前我会再加这样一行:
: line[SIZE*5-1] = '\0';
: 好, 这样一来这个 line buffer 应该就不会因为 input 的单行太长
: 而给你带来麻烦了...
$ man 3 fgets
fgets() reads in at most
one less than size characters from stream and
stores them into the buffer pointed to by s. Reading stops after an
EOF or a newline. If a newline is read, it is stored into the buffer.
A '\0' is stored after the last character in the buffer.
所以不用担心 把那个分号收起来好好利用吧 :)
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 218.167.182.90
※ 编辑: scwg 来自: 218.167.182.90 (11/20 20:38)
1F:→ euphrate:了 推 61.230.37.1 11/20