输出内容时后面显示乱码

使用文件操作函数时,我遇到过几次,打印内容时内容没有错误,可是末尾多显示了几个乱码,其实主要是因为字符串末尾没有赋字符串结束符号

[root@bogon mycode]# cat a.c
#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#define MAX_SIZE 40
int main()
{
    char buf[MAX_SIZE];
    //char buf[MAX_SIZE+1];
    read(STDIN_FILENO,buf,MAX_SIZE);
    //buf[MAX_SIZE]='';//如果末尾多了些乱码,可以在末尾添加0,把前面的定义buf那里换成注释掉的那条语句
    printf("buf is: %s",buf);
    return 0;
}
[root@bogon mycode]# ./a.out
linux
buf is: linux
[root@bogon mycode]# 
原文地址:https://www.cnblogs.com/biaopei/p/7730632.html