输出内容时后面显示乱码

来源:互联网 发布:知乎发帖注意事项 编辑:程序博客网 时间:2024/05/21 12:42

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

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