我正在尝试读取一个程序,该程序使用 read() 从文件中读取 N 个字节,并使用 write() 在 STDOUT 中打印它们。问题是,用户还可以指定 block 大小,默认情况下它是 1024,最多只能达到 1048576。我必须将读取的内容存储在缓冲区中,但该缓冲区不能与我读取的字节大小相同必须阅读,否则,我可能会创建一个对于堆栈大小来说太大的缓冲区。因此,我创建了一个与 block 大小一样大的缓冲区,这样我就可以读取直到它已满,写入然后再次读取到缓冲区的开头。
所有这一切的问题在于它肯定无法按预期工作,我很确定必须有更简单的方法来做到这一点。
相关代码:
void run_hd_b (int b, int fd, int BSIZE){
int res_read; //result from write
int res_write; //result from read
int read_bytes = 0;
char buffer[BSIZE];
int i = 0;
int count = 0;
if (b < BSIZE) count = b;
else count = BSIZE;
while (read_bytes < b && (res_read = read(fd, &buffer[i], count)) != 0){
if (res_read == BSIZE){
i = 0;
}
else i = res_read;
read_bytes += res_read;
while((res_write = write(1, buffer, res_read)) < res_read);
}
}
最佳答案
下面是您的循环的修订版本,它可以编译(并且可能有效),然后是一些注释。
#include <assert.h>
#include <unistd.h>
void run_hd_n (int n, int fd, int BSIZE) {
int res_read;
char buffer[BSIZE];
// can only get up to 1048576
assert(BSIZE <= 1048576);
for( int read_bytes=0; read_bytes < n; read_bytes += res_read ) {
if( (res_read = read(fd, buffer, BSIZE)) < BSIZE ) {
if( res_read == 0 ) return; // EOF or error
}
if( write(STDOUT_FILENO, buffer, res_read) < res_read ) return;
}
}
- 我将
b
更改为n
超出惯例。 - 紧跟标准。 read(2) 和write(2) 采用
size_t
,而不是int
。如果使用n == -1
调用,您的程序将如何 react ? - 如果您有已知的强加约束,请将其包含在某处。您声明了 BSIZE 的最大大小;我使用
assert
来执行它。 - 我无法判断您的问题是关于分配空间还是复制数据。我选择解决后者。
- 读取小于缓冲区的完整大小不是错误。无需使用
count
来计算。只是阅读,看看你有没有什么。 - 您已经编写了一个返回类型为
void
的 I/O 函数。调用者将如何得知发生了什么?我会返回res_read
并让调用者测试他是否读取了请求的数量,否则请咨询errno
。
关于c - 从文件中读取 N 个字节并使用 read() 和 write() 打印它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52975233/