Implementing the “more” Unix utility command

非 Y 不嫁゛ 提交于 2019-12-12 12:22:12

问题


i am trying to implement the more command. I want to learn that how can I understand if there is a pipe. For example, if I type from the shell

cat file1 file2 | more

how can I handle that inside the implementation of more?

And is the implementation of more available as open source?

Actually i could not succeed from reading stdin.I've managed doing more file.txt but not cat file | more..

i think i should first read from user and put a buffer than print the buffer. my code contains:

if(argc == 1)
{
  fgets(line, 255, 0);
   printf("%s", line);
} 

but it gives error.


回答1:


The more syntax is

more [options] [file_name]

If you don't provide a file name, the more command gets input from stdin; you can provide this input (via stdin) using a pipe, for example:

cat file.txt | more

This sends the output of the cat command to more. This is the same as doing:

more file.txt

You don't need to specifically know if there is a pipe or not; you just need to check if a filename was passed as argument to more. If so, the input is considered to be the contents of the file. If not, the input is considered to originate from stdin.

As for the source code, some google searching will take you a long way. Here is some old source code from FreeBSD:

http://svnweb.freebsd.org/base/stable/2.0.5/usr.bin/more/

Or more recente source from the Ubuntu repositories:

http://bazaar.launchpad.net/~vcs-imports/util-linux-ng/trunk/files/head:/text-utils/




回答2:


suggest u first check the argc whether equal 1, if equal 1 ,you shoule use the stdin as your inpout file handle, so your program can handle the situation as cat file.txt | more



来源:https://stackoverflow.com/questions/9854267/implementing-the-more-unix-utility-command

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!