日期:2014-05-16  浏览次数:20675 次

急求:unix I/O read函数读取时发生错误
  #include <unistd.h>
  #include <sys/types.h>
  #include <string.h>
  #include <sys/stat.h>
  #include <fcntl.h>
  #include <stdio.h>
  int main()
  {
      char buf[20] = {0};
  
      int fd1;
      int num;
      fd1 = open("test.txt", O_RDONLY, 0);
      while((num = read(fd1, buf, 19)) > 0)
      {
              buf[19] = '\0';
              printf("num:%d,buf:%s\n",num,buf);
      }
      if(num <0)
          printf("read error\n");
      else if(num == 0)
          printf("read eof of file\n ");
      else//读取数据不足 指定数据19时 
      {
          printf("num:%d,buf:%s\n",num,buf);
          num = read(fd1, buf, 19);//再度一次,确定是否读取完毕
          if(num == 0)
              printf("read eof of file\n ");
         else
             printf("read error\n");
     }
      return 0;
  }


读取结果:
num:19,buf:sdfsafnkkkkksdfs;ek
num:19,buf:sdfm sdfneiskan sfe
num:19,buf:lalnf adfefsdfadn a
num:19,buf:klefna fsadadesascf
num:4,buf:ens
na fsadadesascf

read eof of file

问题:不懂 为什么  红字中  buf中 num=4?  在读取19个时,我需要自己 buf[19] = '\0'表字符串结束。 当读取不足时,系统自动在数组末尾添加 '\0'吗?  另外,最后面的 na fsadadesascf  又是怎么出来的啊?
Unix?i/o read

------解决方案--------------------
while((num = read(fd1, buf, 19)) > 0)
      {
              buf[19] = '\0';
              printf("num:%d,buf:%s\n",num,buf);
      }

这一段不是明显的错误吗。

buf[num] = '\0'才对。