gpt4 book ai didi

c - C 中的 Unix HEAD 命令实现在较大的行上失败

转载 作者:太空宇宙 更新时间:2023-11-04 01:19:50 25 4
gpt4 key购买 nike

我目前正在用 C 实现 Unix HEAD 命令,并且只使用系统函数。到目前为止,它可以完美地处理文件,这些文件的行长度小于 我为我的 buffer 指定的行:

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define LINES_TO_READ 10
#define BUFF_SIZE 4096

int main(int argc, char const *argv[]) {
for (ssize_t i = 1; i < argc; i++) {
const char *filename = argv[i];

int fd = open(filename, O_RDONLY);

if (fd < 0) {
perror("open");
return -1;
}

char ch, buffer[BUFF_SIZE];
size_t index = 0, lines = 1;
ssize_t rresult, wresult;

// Read the file byte by byte
while ((rresult = read(fd, &ch, 1)) != 0) {
if (rresult < 0) {
perror("read");
return -1;
}

// Check if the current character is a new line (the line ends here)
if (ch == '\n') {
buffer[index] = ch;
buffer[index + 1] = '\0';
ch = 0;
index = 0;

// Print the line
wresult = 0;
ssize_t buffer_length = strlen(buffer);
while (wresult != buffer_length) {
ssize_t res = write(STDOUT_FILENO, buffer + wresult, buffer_length - wresult);

if (wresult < 0) {
perror("write");
return -1;
}

wresult += res;
}

// Stop if we read 10 lines already
if (lines == LINES_TO_READ) {
break;
}

lines++;
} else {
buffer[index++] = ch;
}
}

if (close(fd) < 0) {
perror("close");
return -1;
}
}

return 0;
}

它适用于行长度小于 BUFF_SIZE(现在设置为 4096)的文件。

如何避免这种情况并使其适用于任何长度的行?

最佳答案

不要一次读取一个字节。将 block (4096 或 8192 字节是合理的大小,或使用 PIPE_BUF(来自 limits.h))读入缓冲区。在计算换行符的同时输出每个字符。如果打印足够多的换行符,则终止。如果您到达缓冲区的末尾并且还没有打印足够的行,请将更多数据读入缓冲区。

关于c - C 中的 Unix HEAD 命令实现在较大的行上失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47041443/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com