使用读写和 lseek 打印文件或标准输入的最后 10 行

Print last 10 lines of file or stdin with read write and lseek

我正在研究 tail 函数的实现,我应该只对 I/O 使用 read()write()lseek(),等等到目前为止,我有这个:

int printFileLines(int fileDesc)
{
    char c; 
    int lineCount = 0, charCount = 0;   
    int pos = 0, rState;
    while(pos != -1 && lineCount < 10)
    {
        if((rState = read(fileDesc, &c, 1)) < 0)
        {
            perror("read:");
        }
        else if(rState == 0) break;
        else
        {
            if(pos == -1)
            {
                pos = lseek(fileDesc, 0, SEEK_END);
            }
            pos--;
            pos=lseek(fileDesc, pos, SEEK_SET); 
            if (c == '\n')
            {
                lineCount++;
            }
            charCount++;
        }
    }

    if (lineCount >= 10)
        lseek(fileDesc, 2, SEEK_CUR);
    else
        lseek(fileDesc, 0, SEEK_SET);

    char *lines = malloc(charCount - 1 * sizeof(char));

    read(fileDesc, lines, charCount);
    lines[charCount - 1] = 10;
    write(STDOUT_FILENO, lines, charCount);

    return 0;
}

到目前为止它适用于超过 10 行的文件,但是当我传递一个少于 10 行的文件时它会停止,它只打印该文件的最后一行,但我无法获取它与 stdin 一起工作。 如果有人能告诉我如何解决这个问题,那就太好了 :D

第一期:

如果您在此处阅读换行符...

if(read(fileDesc, &c, 1) < 0)
{
    perror("read:");
}

...然后直接设置位置到换行符前面的字符...

pos--;
pos=lseek(fileDesc, pos, SEEK_SET);

然后 linecount>= 10(while-loop 终止),然后您读取的第一个字符是最后一个换行符之前的行的最后一个字符。换行符本身也不是最后 10 行的一部分,因此只需从当前流位置跳过两个字符:

if (linecount >= 10)
    lseek(fileDesc, 2, SEEK_CUR);

第二期:

假设流偏移量已到达流的开头:

pos--;
pos=lseek(fileDesc, pos, SEEK_SET); // pos is now 0

while-condition 仍然是 TRUE:

while(pos != -1 && lineCount < 10)

现在读取了一个字符。在此之后,文件偏移量为1(第二个字符):

if(read(fileDesc, &c, 1) < 0)
{
    perror("read:");
}

在这里,pos 下降到 -1,lseek 将 失败:

pos--;
pos=lseek(fileDesc, pos, SEEK_SET); 

由于 lseek 失败,文件中的位置现在是 second 字符,因此缺少第一个字符。如果在 while-loop 之后 pos == -1:

,则通过将文件偏移重置为文件开头来解决此问题
if (linecount >= 10)
    lseek(fileDesc, 2, SEEK_CUR);
else
    lseek(fileDesc, 0, SEEK_SET);

性能:

这需要很多system-calls。一个简单的增强是使用缓冲的 f* 函数:

FILE *f = fdopen(fileDesc, "r");
fseek(...);
fgetc(...);

等此外,这不需要 system-specific 函数。

更好的方法是逐块向后读取文件并对这些块进行操作,但这需要更多的编码工作。

对于 Unix,您还可以 mmap() 整个文件并在内存中向后搜索换行符。