【发布时间】: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 进行硬编码。格式也是……特殊,至少可以这么说。