LinuxSir.cn,穿越时空的Linuxsir!

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

简单copy程序问题?

[复制链接]
发表于 2003-6-13 15:40:51 | 显示全部楼层 |阅读模式
//linux 程序设计,copy改

  1. //a single copy program
  2. #include<unistd.h>
  3. #include<sys/stat.h>
  4. #include<fcntl.h>
  5. #include<stdlib.h>

  6. int main()
  7. {
  8.         char *c;
  9.         int size;//buffer大小
  10.         int in,out;
  11.         int nread;
  12.         int nwrited=0;
  13.         printf("input the size buffer:\n");
  14.         scanf("%d",&size);
  15.         c=(char*)(malloc(sizeof(size*sizeof(char))));
  16.         in=open("re3.mp3",O_RDONLY);
  17.                     out=open("re32.mp3",O_WRONLY|O_CREAT,S_IRUSR|S_IXUSR|S_IRGRP|S_IRGRP);
  18.         while(nread=read(in,c,size)>0)
  19.         {
  20. //                printf("nread value: %d\n",nread);
  21. //                sleep(1);
  22. //                printf("writed%d\n",write(out,c,nread));
  23.                 write(out,c,nread);
  24.         }
  25.         return 0;       

  26. }
复制代码

gcc 3.2 redhat X环境
为甚么只有输入为1时,才能copy                       
其他情况输入(如10,100)每次也只copy一个字符?
发表于 2003-6-13 15:59:43 | 显示全部楼层
c=(char*)(malloc(sizeof(size*sizeof(char))));
应该是 c=(char*)malloc(size*sizeof(char));吧,否则malloc始终都分配4个字符的空间。

另:帖代码的时候注意缩进,看看论坛的vB码说明。
 楼主| 发表于 2003-6-13 17:18:32 | 显示全部楼层
好,
这个的错误太低级了,哈哈,可能复制时搞错了。
//代码宿进已修正
 楼主| 发表于 2003-6-13 18:19:46 | 显示全部楼层
修改后
  1. #include<unistd.h>
  2. #include<sys/stat.h>
  3. #include<fcntl.h>
  4. #include<stdlib.h>
  5. int main()
  6. {
  7.         char *c;
  8.         int size;
  9.         int in,out;
  10.         int nread;
  11.         int nwrited=0;
  12.         printf("input the size buffer:\n");
  13.         scanf("%d",&size);
  14.         c=(char*)malloc(size*sizeof(char));
  15.         in=open("re3.mp3",O_RDONLY);
  16.         out=open("re32.mp3",O_WRONLY|O_CREAT,S_IRUSR|S_IXUSR|S_IRGRP|S_IRGRP);
  17.         while(nread=read(in,c,size)>0)
  18.         {
  19.         //        printf("nread value:%d\n",nread);
  20. //                sleep(1);
  21.         //        printf("writed%d\n",write(out,c,nread));
  22.                 write(out,c,nread);
  23.         }
  24.         return 0;       
  25. }
复制代码
还不行 关键好像nread总等于1而不是等于4或其他
发表于 2003-6-13 21:56:27 | 显示全部楼层
while(nread=read(in,c,size)>0)
应该是:
while((nread=read(in,c,size))>0)
否则nread = (read(int,c,size) > 0),就是1
 楼主| 发表于 2003-6-13 23:28:51 | 显示全部楼层
原来如此,
呵呵,又是低级错误(刚学)。
多谢!
您需要登录后才可以回帖 登录 | 注册

本版积分规则

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