输出内容时后面显示乱码

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

[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';//如果末尾多了些乱码,可以在末尾添加\0,把前面的定义buf那里换成注释掉的那条语句
    printf("buf is: %s",buf);
    return 0;
}
[root@bogon mycode]# ./a.out
linux
buf is: linux
[root@bogon mycode]# 

posted on 2017-10-25 18:06  标配的小号  阅读(194)  评论(0编辑  收藏  举报

导航