简体   繁体   English

使用系统调用从终端读取 t 并输出输入的最后 6 行

[英]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).我必须仅使用 C 中的系统调用(对于 Linux)从终端读取一些文本,然后输出最后 6 行(就像 linux 中的 tail 命令一样)。 How do I do that?我怎么做? If the file is smaller than 6 lines, the whole files should be outputed.如果文件小于 6 行,则应输出整个文件。 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.使用 read()、dup() 和 close() 解决了我的问题。

how about : while(read(STDIN_FILENO, &ch, 1) > 0) as a start?怎么样: while(read(STDIN_FILENO, &ch, 1) > 0) 作为开始? 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().了解基本的系统调用,如 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.我考虑到文件中只有 10 个不存在,因此发布了我的代码,您可以将其设为通用。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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