LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 753|回复: 5

求助

[复制链接]
发表于 2003-12-3 19:12:49 | 显示全部楼层 |阅读模式
各位大侠,我遇到问题了:下面的程序运行结果不是我所预料的
   #include
    ……
   #include
    int fd,receive;
    char buf[5];
    fd=open("receive",O_RDWR|O_CREAT);
    write(fd,"abc\r",4);
    read(fd,buf,5);
    printf("%s\n",buf);
为什么最后的运行结果不是abc呢?我非常头疼,请大家指点指点吧:help
发表于 2003-12-5 22:22:22 | 显示全部楼层

回复: 求助

  1. int main()
  2. {
  3.         int fd,i=0,j=0;
  4.         char buf[5];
  5.        if((fd=open("receive",O_RDWR|O_CREAT,0644))==-1){
  6.                 printf("open file error!\n");
  7.                 return;
  8.         }
  9.         if((i=write(fd,"abc\r",[color=red]5[/color] ))==0){//当把5变成更大的数,如10或。。。执行less receive,有趣的事会发生!!
  10.                 printf("write error!\n");
  11.                 exit(1);
  12.         }
  13.        [color=red] //close(fd);
  14.         //fd=open("receive",O_RDONLY);[/color]
  15.         if((j=read(fd,buf,5))==0){
  16.                 printf("read error!\n");
  17.                 exit(1);
  18.         }
  19.         printf("i=%d,j=%d,%s\n",i,j,buf);
  20.         close(fd);
  21. }
复制代码

试试这段代码
再试试去掉注释后的代码
发表于 2003-12-5 22:39:56 | 显示全部楼层

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <sys/types.h>
  4. #include <unistd.h>
  5. #include <sys/stat.h>
  6. #include <fcntl.h>

  7. int
  8. main(void)
  9. {
  10.   int fd, n;
  11.   char buf[5];
  12.   
  13.   fd = open("receive", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
  14.   [color=red]/* 有O_CREAT标志应该有第三个参数(权限) */[/color]
  15.   write(fd, "abc", 4); [color=red]/* 不需要\r,如果要加就加\n */[/color]
  16.   lseek(fd, 0, SEEK_SET); [color=red]/* 必需把文件读写位置移到开头,你的错误主要就是因为这个 */[/color]
  17.   n = read(fd, buf, 5);
  18.   buf[n] = '\0'; [color=red]/* 读入的字符串没有结尾的\0,必需自己加 */[/color]
  19.   printf("%s\n", buf); [color=red]/* 上面写入文件的字符串没有\n所以这里加一个,如果有\n这里就不用了 */[/color]

  20.   exit(0);
  21. }
复制代码
 楼主| 发表于 2003-12-11 17:02:17 | 显示全部楼层
多谢各位,我知道了!
发表于 2003-12-11 17:42:21 | 显示全部楼层
rewind
发表于 2003-12-14 00:18:40 | 显示全部楼层
解释的好详细,佩服。
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表