簡體   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