【问题标题】:Copying files content in C在 C 中复制文件内容
【发布时间】:2021-12-16 22:35:38
【问题描述】:
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 语句但不是最后一个的原因,为什么我们必须再次读取文件?

【问题讨论】:

  • 你从哪里得到这个代码?它似乎是用 MS Word 或类似的东西编写的……你能发布实际编译的代码吗?
  • 顺便说一句,这不是很好的代码; read 操作可以去重复,并且您通常会避免使用常量或使用sizeof buff 在任何地方对幻数 256 进行硬编码。格式也是……特殊,至少可以这么说。

标签: c linux file


【解决方案1】:

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

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

【讨论】:

  • 假设我们只想使用这段代码来读取256字节以下的文件,那么循环就不需要了,对吧?
  • @LightLamps 是的,没错。
猜你喜欢
  • 2013-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-24
  • 1970-01-01
  • 1970-01-01
  • 2012-12-12
相关资源
最近更新 更多