snprintf函数截断问题

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>

int main()
{
    //printf("Hello World");
    char buff[12] = {0};
    snprintf(buff,sizeof(buff),"%s\n","hello world");
    printf("the %s an the \n",buff);
    return 0;
}

在编译阶段会报出字符阶段的错误,

main.c:18:37: warning: ‘snprintf’ output truncated before the last format character [-Wformat-truncation=]
   18 |     snprintf(buff,sizeof(buff),"%s\n","hello world");
      |                                     ^
main.c:18:5: note: ‘snprintf’ output 13 bytes into a destination of size 12
   18 |     snprintf(buff,sizeof(buff),"%s\n","hello world");
      |     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
the hello world an the 

运行可以看到最后的\n并没有写入到buff中导致字符发生了截断

修改只需要在字符串的长度上加上尾零的长度和\n字符的长度

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>

int main()
{
    //printf("Hello World");
    char buff[13] = {0};
    snprintf(buff,sizeof(buff),"%s\n","hello world");
    printf("the %s an the sizeoof(hello world) is %ld\n",buff,sizeof("hello world"));
    return 0;
}

the hello world
 an the sizeoof(hello world) is 12

在文件的写入中如果没有好的注意到这些小的问题会导致文件没有按自己的格式写入,接着导致文件的读取错误 

上一篇:CF936D World of Tank


下一篇:拍照时如何有效预防抖动?8个简单实用方法教你有效防抖