Search code examples
coperating-systemsystem-callstail

read tfrom terminal using system calls and output last 6 lines of the input


I have to read from terminal some text using only system calls(for Linux) in C and then output the last 6 lines(just like the tail command in linux). How do I do that? If the file is smaller than 6 lines, the whole files should be outputed. The output should be with write.

Sample input:

1
2
344444
44444
555555555555555555555555555555555555
6
7
8
9
100000
11

OUTPUT:

6
7
8
9
100000
11

Using read(), dup() & close() fixed my problem.


Solution

  • learn about basic system call like read(), dup() & close(). open man pages & check how these system calls are working . I posted my code by considering that only 10 no are there in file, you can make it generic.

    #include <stdio.h>
    #include <unistd.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    
    int main(int argc, char * argv[])
    {
            int a[10], i, n;
            n = sizeof(a)/ sizeof(a[0]);
            int fd ;
            close(0);// close STDIN so that scanf will read from file
            fd=open(argv[1],O_RDWR | 0664);
    
            if(fd==-1)
            {
                perror("open");
                return 0;
            }
    
            for(i=0;i<n;i++) scanf("%d",&a[i]);
    
            //print only last 6 lines
            for(i=n-1;i>n-6;i--) printf("%d\n",a[i]);
    
            return 0;
    }