读&写系统调用总是返回1

时间:2015-04-16 13:29:48

标签: c linux

我需要将一个文件的内容复制到另一个文件。但问题是我正在阅读和阅读始终写入返回值1.但是读取缓冲区数据。有人可以解释这里出了什么问题吗? 我正在使用gcc编译器。

#include<stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include<string.h>
int copy_file_to_file(int,int);
int main()
{
    int src_fd,dst_fd;
    if ( (src_fd = open("source.txt",O_RDONLY)) == -1 )
    {
       printf("file opening error");
       return -1;
    }
    if( (dst_fd = open("destination.txt",O_WRONLY | O_CREAT,0644)) == -1 )
   {
       printf("destination file opening error\n");
       return -1;
   }
   copy_file_to_file(src_fd,dst_fd);
   close(src_fd);
   close(dst_fd);
   return 0;
}

int copy_file_to_file(int source_fd,int dest_fd)
{
    int byte_read, byte_write;
    char buf[10];

    while((byte_read = read(source_fd, buf, 10)>0) )
   {

      byte_write=write(dest_fd, buf, byte_read);
      printf("buf=%s byte_read = %d byte_write=%d \n",buf,byte_read,byte_write);
   }
  return 0;
}

输出: -

buf=Hello world

我在工作  byte_read = 1 byte_write=1

1 个答案:

答案 0 :(得分:8)

while((byte_read = read(source_fd, buf, 10)>0) )

被解释为(br = (read() > 0))

修正:

while((byte_read = read(source_fd, buf, 10)) > 0)

Operator precedence

相关问题