fgets 何时危险(大小小于缓冲区大小)?
When fgets is dangerous (with the size less than buffer size)?
FILE * file = fopen( “in.txt”, “r” );
char line[80];
if( NULL != file ) {
fgets( line, 40, file );
fclose( file );
}
上面的代码有什么危险吗,我在这里看到的是它得到了最大长度为 40 的字符串到缓冲区行然后关闭文件。
您可能会混淆 fgets()
和 gets()
。参见 Why is the gets function so dangerous that it should not be used?
只要大小参数与缓冲区大小匹配,fgets
就是安全的。在您的情况下, fgets( line, sizeof(line), file );
是正常的
注意:fgets()
最多读到比"size"少1,总是0终止。
FILE * file = fopen( “in.txt”, “r” );
char line[80];
if( NULL != file ) {
fgets( line, 40, file );
fclose( file );
}
上面的代码有什么危险吗,我在这里看到的是它得到了最大长度为 40 的字符串到缓冲区行然后关闭文件。
您可能会混淆 fgets()
和 gets()
。参见 Why is the gets function so dangerous that it should not be used?
只要大小参数与缓冲区大小匹配,fgets
就是安全的。在您的情况下, fgets( line, sizeof(line), file );
是正常的
注意:fgets()
最多读到比"size"少1,总是0终止。