Google Interview Question
Software Engineer / DevelopersThough I don't need tail anymore, I know that it does not print lines in reverse order. :(
generally, use the round-robin % ...the number of lines required is what to be modular-ed.
void tail(FILE *fp, int num_lines)
{
char **buffer = calloc(num_lines, sizeof(char *));
int index = 0;
int i;
for (;;)
{
char *line = NULL;
int len = 0;
if (getline(&line, &len, fp) < 0)
break;
if (buffer[index])
free(buffer[index]);
buffer[index] = line;
index++;
index %= num_lines;
}
for (i = 0; i < num_lines; i++)
puts(buffer[(index + i) % num_lines]);
}
Use fseek() function in C. Using fseek(), if you pass negative number, then file pointer moves that number of bytes to its left, and if positive number passed, then it shifts that many bytes right.
- Ankul August 18, 2010First reach end of file using fseek(fp,0,SEEK_END) then keep coming 1 char left and appending chars to string end, each time u find a '\n', reverse the string and print it, again make the string empty and do this until required number of lines are not printed :)