I'm working on an implementation of the tail function and I'm only supposed to use read()
, write()
and lseek()
for I/O, and so far I have this:
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;
}
So far it works for files that have more than 10 lines, but it brakes when i pass a file with less than 10 lines, it just prints the last line of that file, and I can't get it to work with stdin
.
If someone can give me an idea how to fix this issues, that'd be great :D