- 论坛徽章:
- 11
|
本帖最后由 Ager 于 2012-10-11 07:57 编辑
@mirnshi
@starwing83
@pmerofc
最近都在讨论gets、fgets的……拿老祖宗的书来看……
由《CMate》里所推的月薪10,000元程序员的代码,引发了C版朋友们的热烈讨论。讨论的焦点,当然就是关于gets、fgets、溢出等等话题。
我就寻思了:这gets/fgets的问题,难道是最近或最近几年或最近十几年才有的吗?
手头材料有限,但是UNIX和C的老祖宗们如B. W. Kernighan和R. Pike的《The UNIX Programming Environment》我还是有一本。
在这本书的第183页,老祖宗们写了这样的代码和说明:- print(fp, pagesize) /* print fp in pagesize chunk */
- FILE *fp;
- int pagesize;
- {
- static int lines = 0; /* number of lines so far */
- char buf[BUFSIZ];
- while (fgets(buf, sizeof buf, fp) != NULL)
- if (++lines < pagesize)
- fputs(buf, stdout);
- else{
- buf[strlen(buf)-1] = '\0';
- fputs(buf, stdout);
- fflush(stdout);
- ttyin();
- lines = 0;
- }
- }
复制代码 (你看看,人家写的代码,多优美……)
We used BUFSIZ, which is defined in <stdio.h>, as the size of the input buffer. fgets(buf,size,fp) fetches the next line of input from fp, up to and including a newline, into buf, and adds a terminating \0; at most size-1 characters are copied. It returns NULL at end of file. (fgets could be better designed: it returns buf instead of a character count; furthermore it provides no warning if the input line was too long. No characters are lost, but you have to look at buf to see what really happened.)
至于gets,翻遍全书(其实看书末的索引就可以),根本就没有这么个东东。
这是一本新书或比较新的书吗?不!这本书非常老旧!1984年出版的!将近三十年了!
2012年了,小乔书里的gets,到底是怎么流传至此的 …… ?
|
|