簡體   English   中英

C語言中的Unix HEAD命令實現在較大行上失敗

[英]Unix HEAD command implementation in C fails on larger lines

我目前正在用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小於BUFF_SIZE (現在設置為4096 )的文件。

如何避免這種情況並使之適用於任何線長?

不要一次讀取一個字節。 將一個塊(4096或8192字節是合理的大小,或使用PIPE_BUF(來自limits.h))讀取到緩沖區中。 在計算換行符時輸出每個字符。 如果您打印足夠的換行符,請終止。 如果到達緩沖區的末端並且沒有打印足夠的行,請向緩沖區中讀取更多數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM