我正在执行的尾部功能,我只是应该使用read()
,write()
和lseek()
I/O,到目前为止,我有这样的:打印最后10行文件或标准输入读写和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
谢谢!!!!!!!!我一直在挣扎几个小时!关于表演的记录,我甚至不会使用这些功能,但这个该死的任务人... – Reaper9806