我想使用 C 语言中的 read() 命令将 20 个字符 block 的文本文件中的数据读入缓冲区,直到文件末尾。
while (n != 0) {
n = read(filedescriptor, buffer, 20);
}
这每次都会覆盖缓冲区。是否可以使用read()
命令追加到缓冲区?
最佳答案
绝对有可能。但你应该确切地知道你的缓冲区有多大。
如果你有
#define BUFFER_SIZE 200
char buf[BUFFER_SIZE];
int nbuf = 0; /* number of characters read into buffer */
int r;
你可以写类似的东西
while(nbuf < BUFFER_SIZE) {
int n_to_read = 20;
if(nread + n_to_read > BUFFER_SIZE) /* make sure won't overflow buffer */
n_to_read = BUFFER_SIZE - nread;
r = read(fd, &buf[nbuf], n_to_read);
if(r <= 0) break; /* error / EOF */
nbuf += r;
}
如果您想展示对 C 中数组和指针之间“等价性”的理解,您可以将 read
调用重写为
r = read(fd, buf + nbuf, n_to_read);
事实上,很多人都会这样写。
附注我会使用 fread
和 FILE *
指针,而不是 read
和整数文件描述符。
关于c - 使用 C 中的 read() 追加到缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34887462/