简体   繁体   中英

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.

how about : while(read(STDIN_FILENO, &ch, 1) > 0) as a start? and you can store the output in buffer and manipulate the lines with some delimiter, and then go backwards on the array.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM