首页 > 解决方案 > 在 C 中复制文件内容

问题描述

int copy( char *from, char *to )    {
    int fd_from, fd_to, rbytes, wbytes;
    char buff[256];
    if( ( fd_from = open( from, O_RDONLY ) ) == -1 )
        { perror( “open from” ); return( - 1 ); }
    if( ( fd_to = open( to, O_WRONLY | O_CREAT, 0664 ) ) == -1 )
        { perror( “open to” ); return( -1 ); }
    if( ( rbytes = read( fd_from, buff, 256 ) ) == -1 )
         { perror( “read 1” ); return( -1 ); }
    while( rbytes > 0 )    {
        if( ( wbytes = write( fd_to, buff, rbytes ) ) == -1 )
            { perror( “write” ); return( -1 ); }
        if( wbytes != rbytes )
            { fprintf( stderr, “bad write\n” ); return( -1 ); }
        if( ( rbytes = read( fd_from, buff, 256 ) ) == -1 )
            { perror( “read 2” ); return( -1 ); }
    }
    close( fd_from ); close( fd_to );  return( 0 );
}

为什么有一个循环来检查 rbytes > 0?

我理解循环内有 2 个 if 语句但不是最后一个语句的原因,为什么我们必须再次读取文件?

标签: clinuxfile

解决方案


为什么有一个循环来检查 rbytes > 0?

因为每个read操作最多只能读取 256 个字节,但大多数文件都比这大。循环继续,直到输入文件被完全读取,此时read将返回 0,循环将终止。


推荐阅读