gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:10:11 32 4
gpt4 key购买 nike

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

示例输入:

1
2
344444
44444
555555555555555555555555555555555555
6
7
8
9
100000
11

输出:

6
7
8
9
100000
11

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

最佳答案

了解基本的系统调用,如 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;
}

关于c - 使用系统调用从终端读取并输出输入的最后 6 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47247009/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com