【发布时间】:2016-01-18 18:40:17
【问题描述】:
我正在实现tail函数,我应该只使用read()、write()和lseek()进行I/O,到目前为止我有这个:
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
【问题讨论】: