Thread: Getting standard input

  1. #1
    Registered User
    Join Date
    Mar 2004

    Getting standard input

    I have problem with combining the two function together.

    For the first while statement, it only applicable for file redirection eg "programname < filename". If i use the first while statement for getting a standard input without the file redirection, the user have to press the control D button in order to exit the while statement.

    As for the second while statement, the user able to enter the standard input manually and then press enter and it will exit the while loop. But for the file redirection, it is only able to get the first line in the file and not the whole file.

    How can i implement a while statement where both the condition will be able to work which means when the user use the file redicrection, it is able to read till the end of the file and also when the user enter the input manually from the standard input and press enter, it will exit from the loop ??

    // used for file input redirection
    while((c = getchar()) != EOF)
    // used for command line input
    while((c = getchar()) != '\n')

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    In short, you can't. Redirection is identical to you typing on the keyboard. There is no difference as far as C is concerned. So, you either have it check for EOF, and the user must then enter EOF themselves, or you have it read one line at a time.

    The closest to getting what you want is going to be setting up some form of prompt:
    printf("If reading from the keyboard, enter something now: ");
    if( (c = getchar() ) == something )
        ...reading from keyboard, use first loop...
        ...reading from file, use second...
    Or, you could so something fun like:
    while( c == something ? (x=getchar()) != '\n' : (x=getchar()) != EOF )
    { whatever...
    But again, there's always the slight chance that the first byte of the piped file matches something, so it throws off your efforts. So in closing, you can try, but there's no guarintee. But really, is it all that much trouble to prompt for CTRL+D from your users?

    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Printing Length of Input and the Limited Input
    By dnguyen1022 in forum C Programming
    Replies: 33
    Last Post: 11-29-2008, 04:13 PM
  2. Standard Input Trouble
    By c_323_h in forum C++ Programming
    Replies: 4
    Last Post: 07-09-2006, 02:14 PM
  3. large program code ,please help
    By Ash1981 in forum C Programming
    Replies: 14
    Last Post: 01-30-2006, 06:16 AM
  4. Custom Made Safe Input Function
    By Beast() in forum C Programming
    Replies: 6
    Last Post: 08-21-2004, 10:19 PM
  5. need help with some input
    By blindleaf in forum C Programming
    Replies: 2
    Last Post: 03-16-2003, 01:50 PM