繁体   English   中英

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

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

我必须仅使用 C 中的系统调用(对于 Linux)从终端读取一些文本,然后输出最后 6 行(就像 linux 中的 tail 命令一样)。 我怎么做? 如果文件小于 6 行,则应输出整个文件。 输出应该是写。

样本输入:

1
2
344444
44444
555555555555555555555555555555555555
6
7
8
9
100000
11

输出:

6
7
8
9
100000
11

使用 read()、dup() 和 close() 解决了我的问题。

怎么样: while(read(STDIN_FILENO, &ch, 1) > 0) 作为开始? 并且您可以将输出存储在缓冲区中并使用一些分隔符操作行,然后在数组上向后移动。

了解基本的系统调用,如 read()、dup() 和 close()。 打开手册页并检查这些系统调用是如何工作的。 我考虑到文件中只有 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