snprintf的困惑
这两天在整理c语言基本函数的一些注意点和用法,整理到snprintf的时候却犯了难,到底应该怎么用?
按理说,要正确使用很简单,至少有两种写法:
#include <stdio.h>
#define BUFSIZ 16
int main(int argc,char **argv)
{
char buf[BUFSIZ];
snprintf(buf, sizeof(buf) - 1, "%s", argv[1]);
buf[sizeof(buf) - 1] = '\0'; /* buf是全局变量或者已经初始化为0时不需要 */
return 0;
}
#define BUFSIZ 16
int main(int argc,char **argv)
{
char buf[BUFSIZ];
snprintf(buf, sizeof(buf) - 1, "%s", argv[1]);
buf[sizeof(buf) - 1] = '\0'; /* buf是全局变量或者已经初始化为0时不需要 */
return 0;
}
或者
#include <stdio.h>
#define BUFSIZ 16
int main(int argc,char **argv)
{
char buf[BUFSIZ];
int ret;
ret = snprintf(buf, sizeof(buf), "%s", argv[1]);
if((ret >= sizeof(buf)) || (ret < 0))
{
/* truncated or error */
buf[sizeof(buf) - 1] = '\0';
}
return 0;
}
#define BUFSIZ 16
int main(int argc,char **argv)
{
char buf[BUFSIZ];
int ret;
ret = snprintf(buf, sizeof(buf), "%s", argv[1]);
if((ret >= sizeof(buf)) || (ret < 0))
{
/* truncated or error */
buf[sizeof(buf) - 1] = '\0';
}
return 0;
}
但是问题在于,这两种写法都很繁琐,在实际使用中几乎没有谁会去这么写。
我手头刚好有一些opensource的代码,便搜索了一便,最后发现基本都是直接调用了snprintf,却没有去检查最后的空结尾的问题;而很多代码都实际是有可能存在此问题的。
那我们在实际写程序的时候到底应该怎么操作呢?
2023年8月07日 03:35
I truly delighted in perusing this post, huge fan. Keep doing awesome me when would you be able to distribute more articles or where would I be able to peruse more on the subject? 먹튀검증사이트
2023年8月09日 04:27
A debt of gratitude is in order for sharing us. Ac repair las vegas
2023年8月28日 06:12
On the off chance that more individuals that compose articles truly fretted about composing incredible substance like you, more perusers would be occupied with their works. Much thanks to you for thinking about your substance. 10
2023年9月03日 07:14
I might want to thank you for the endeavors you have made in composing this article. I am trusting the same best work from you later on too. Much obliged... 먹튀검증업체순위
2023年10月04日 03:35
More often than not I don't make remarks on sites, yet I'd like to say this article truly constrained me to do as such. Truly pleasant post! www.mt-spot.com
2023年11月01日 21:24
It’s perfect time to make some plans for the future and it is time to be happy. I’ve read this post and if I could I wish to suggest you few interesting things or suggestions. Perhaps you could write next articles referring to this article. I want to read more things about it! Sports leggings