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

while循环中调用write()函数,为什么只执行一次?
函数如下所示,在while循环中,从发fd1 read()一个字节数据(如“a”),通过lseek设置fd2的偏移量,然后write() fd2 ;在本程序中共执行10次循环,fd2 应该被写入了十次数据,且每次写入的数据位置不同,也就是fd2中应该有10个“a”,但是fd2中只有1个
我感觉好像是lseek()或write()在10次循环中只运行了一次,为什么?

如果不使用循环,lseek()或write()顺序写,这样fd2中的数据就正常了

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(int argc,char* argv[]){
  int fd1,fd2;
  char buffer[100];
  long offset=0;
  int num,i;

  if(argc!=3){
  printf("Usage : %s source dest",argv[0]);
  return 1;
  }

  if((fd1=open(argv[1],O_RDONLY))==-1){
  perror("Cannot open the file");
  return 1;
  }

  if((fd2=open(argv[2],O_CREAT | O_WRONLY,0777))==-1){
  perror("Cannot create the destination file");
  return 1;
  }

  i=10;

  while(i--){

  printf("offset=%d\n",offset);

  num=read(fd1,buffer,10);

  if(lseek(fd2,offset,SEEK_SET)==-1){
  perror("Cannot move the file pointer");
  return 1;
  }
   
  if(write(fd2,buffer,num)==-1){
  perror("Cannot write the file content to the file");
  return 1;
  }

  offset=offset+20;

  if(lseek(fd2,offset,SEEK_SET)==-1){
  perror("Cannot move the file pointer");
  return 1;
  }

  if(write(fd2,buffer,num)==-1){
  perror("Cannot write the file content to the file");
  return 1;
  }
   
   
  }

  close(fd1);
  close(fd2);
  return 0;
}

------解决方案--------------------
num=read(fd1,buffer,10);

你把read放在循环里了,fd1对应的文件内容太短了吧
循环一次就全读完了,然后下次循环读不到数据,自然什么也没写进去,每次write的num都是0

如果文件大些就正常了吧
又或者我猜你的意思应该是把这行read放在while上面?