c - 在 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 语句但不是最后一个语句的原因,为什么我们必须再次读取文件?
解决方案
为什么有一个循环来检查 rbytes > 0?
因为每个read
操作最多只能读取 256 个字节,但大多数文件都比这大。循环继续,直到输入文件被完全读取,此时read
将返回 0,循环将终止。
推荐阅读
- vue.js - CASL 在 Vue 生产模式下无法正常工作
- bash - Bash 重定向 stdout 和 stderr 以使用时间戳分隔文件
- javafx - 在 Jar 中为 Gluon Scene Builder 11.00 创建自定义控件
- php - 无论如何要通过 WP-Config.php 做到这一点?(通配符重定向除了 wp-admin)
- c# - 如何根据日历月的变化增加 int 变量
- go - 打印 time.Time 时出现意外输出
- android - 第一个活动到第二个活动(意图、数据库和适配器)
- c# - 模拟 IScheduler 进行单元测试
- java - 为什么这个 Spring 应用程序不起作用?
- java - 无法在选项卡布局中创建动态选项卡