Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 400
  • Last Modified:

c problem - pipe vs stdin

Hi,

I'm trying to create a UNIX more-like program (a simple one) and having some problems here.  The program should list 20 lines everytimes a key is pressed.

It should run both way whether by specifying a file name as well as piping from other source :
> more file
> cat file | more.

But for the time being its only work for (i guess)
> more file

If i do
>cat file | more
it doesnt stop waiting for key to be pressed by me. I have specified pipe as /dev/stdin, i guess its just read whatever character from pipe and proceed listing the next 20 lines....till the end.

My question:
1. How to tell the different between pipe output and char from keyboard and of course then to solve the problem.

This is my short program
####################

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>

int main(int argc, char** argv)
{
        /*if (1 == argc) {
                printf("Usage: more [<filename>]\n");
                exit(1);
        }*/

        FILE* fp;
        if (2 == argc) {
                printf("Opening file\n");
                if ((fp = fopen(argv[1], "rt")) == NULL) {
                        perror(" ");
                        exit(1);
                }
        } else if (1 == argc) {
                printf("Opening stdin\n");
                if ((fp = fopen("/dev/stdin", "rt")) == NULL) {
                        //printf("Usage: more [<filename>]\n");
                        perror(" ");
                        exit(1);
                }
        }

        char rtn[20];
        char line[20][256];

        do {
                for (int i=0; i<20; i++) {
                        if (fgets(line[i], 256, fp) != NULL) {
                                printf("%s", line[i]);
                        } else {
                                return 0;
                        }
                }
                /* wait for any key(s) and return are pressed */
                scanf("%s", rtn);
        } while (strcmp (rtn, "q"));
}
#####################################
0
mafendee
Asked:
mafendee
  • 8
  • 7
  • 3
  • +1
1 Solution
 
obgCommented:
Well, to keep it simple...

FILE *fp

if (argc == 1)
  fp = stdin;
else
  fp = fopen(argv[1], "r");

Then use getch() to read the key. It's defined within the curses/ncurses library.
0
 
mafendeeAuthor Commented:
I am not sure whether getch() works on Solaris or not. I got an error message. Anyway, I think getch() will only read one character and might have trouble there to handle input string from user.
0
 
obgCommented:
You'll have to link in the curses library as well, specifying -lcurses... To read a string, use getstr. Look up man curses or man ncurses to see if it's installed or not.
0
Managing Security Policy in a Changing Environment

The enterprise network environment is evolving rapidly as companies extend their physical data centers to embrace cloud computing and software-defined networking. This new reality means that the challenge of managing the security policy is much more dynamic and complex.

 
obgCommented:
curses needs some initialization before you can use it. I found this in a program I wrote about a year ago:

   initscr();
   nonl();
   cbreak();
   noecho();
   standend();
   clear();
   keypad(stdscr, 1);

Before program termination, you should call:

   erase();
   endwin();
0
 
BlackDiamondCommented:
you can also use getchar() <stdio.h> to do the same thing if you don't want to use the curses library.
0
 
obgCommented:
Yeah... I almost fell in that trap myself... Does getchar() not read from stdin?
0
 
mafendeeAuthor Commented:
I did use getchar() but the problem is it didn't stop for every 20 lines waiting for the next key pressed. Just go on till the end. Most probably, it can tell no different between input from keyboard and input from pipe. Both are from stdin, i guess.
I would need some time to read materials on 'curses.h' unless you have a better idea with getchar().
0
 
BlackDiamondCommented:
You are correct.  Try doing an fflush(stdin) before getchar.
0
 
obgCommented:
Ok, what do you think will happen when you do the following?
more < file
0
 
mafendeeAuthor Commented:
Have tried fflush(stdin), doesnt work neither!
0
 
mafendeeAuthor Commented:
obg, I have tried

> more < file

and it didnt wait neither. Just go on till the end.
0
 
obgCommented:
Whenever you do more < file or prog | more or something like that, stdin gets redirected and will no longer be connected to the keyboard. That's why you can't use stdin for keyboard input. Once again, curses supply good functionality for direct keyboard access (and a lot of useful stuff regarding text screen manipulation).
0
 
ecwCommented:
open /dev/tty, set tty setting for single har input and away you go.
0
 
obgCommented:
Say what...?

Maybe I'm stupid, but I don't understand anything of what you just said. The problem as I see it is that regular reading of the file data might come from stdin, and so does the keyboard input (with the regular getc/getchar). Changing the /dev/tty settings will not change that in any way I can see.

Maybe you are suggesting a way to make keyboard input non-buffered, so that you don't need to press return? Well, that would be one step, but on a dead end...
0
 
ecwCommented:
When you say you are writing a "UNIX more-like" program, do you mean you a writing a UNIX program to imitate more, or you are writing non-UNIX (maybe DOS) program that imitates UNIX's more.

If it is an interactive UNIX program, stdin will by default be /dev/tty, a pseudo device that maps to your current tty.  Any program that opens /dev/tty will automagically open it's own tty.  This is used by things like more that act as filters AND require keyboard input.  With more, if argc==1, read from stdin, but whether reading from stdin or not, always get keyboard input from /dev/tty.

You don't ned to use stdio for simple unbuffer3ed single char input, read(2) is fine, use ioctl or tc{get,set}* or derivitives of, for setting the tty raw, min chars to 1, timeout to indefinite.

I'd include and example but haven't access to my Unix boxes today.

A warning though, if you mess with terminal settings, you MUST reset them at program exit, be it by a signal or intended.
0
 
obgCommented:
Ah... Now I see what you mean. Of course... Why didn't I think of that? Well, you don't need to answer that question. ;-)
0
 
mafendeeAuthor Commented:
I managed to get it work with ecw advice. The way I did was, if the number of argument is
a. 1 then
   (fp = fopen("/dev/stdin", "rt")) == NULL) || ((fret = fopen("/dev/tty", "r") = NULL)

// reading input stdin and wait for return from tty

b  2 then
   (fp = fopen(argv[1], "rt")) == NULL) || ((fret = fopen("/dev/tty", "r") == NULL)

// reading input from a file and wait for return from tty


Thanx
0
 
mafendeeAuthor Commented:
But I do not understand from "ecw" message

"You don't ned to use stdio for simple unbuffer3ed single char input, read(2) is fine, use ioctl or tc{get,set}*
or derivitives of, for setting the tty raw, min chars to 1, timeout to indefinite."

What do you mean? and what do I have to do here with tty?
any example would be good.
0
 
ecwCommented:
if you want single char input (ie. hit spcae for next page), stdio will not do.  You have to use termios to change the tty settings to return from read when a single char has been entered.

ie.

int ttyfd;
int quit = 0;
char c;
struct termios termios_old;
struct termios termios_new;

  tty_fd = open("/dev/tty", O_RDONLY);
  tcgetattr(tty_fd, &termios_old);
  termios_new = termios_old;
  termios_new.c_lflag &= ~ICANON;
  termios_new.c_cc[VMIN] = 1;
  termios_new.c_cc[VTIME] = 0;
  /* before doing this, you should set up a signal */
  /* signal handler to reset tty setting to */
  /* termios_old.  Or disable SIG{INT,QUIT,TERM} */
  tcsetattr(tty_fd, TCASNOW, &termios_new);
  /* now drop to pseudo code.... */
  while (! quit) {
   show_next_page();
   printf("More:"); fflush(stdout);
   if (read(tty_fd, c, 1) > 0) {
    /* do what you is expect if char is space, newline, */
    /* q, h, ...., etc. */
   } else {
     quit = 1;
   }
  }
  tcsetattr(tty_fd, TCASNOW, &termios_old);


See the man pages for termios and tcgetattr
0
 
mafendeeAuthor Commented:
Its worked. Thanx a lot guys!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Build your data science skills into a career

Are you ready to take your data science career to the next step, or break into data science? With Springboard’s Data Science Career Track, you’ll master data science topics, have personalized career guidance, weekly calls with a data science expert, and a job guarantee.

  • 8
  • 7
  • 3
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now