473,387 Members | 1,925 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

how to check stdin for piped data

Hi,
I would like to be able to either pipe data into my prog from stdin or get data from a file.
If I try to check by using
Expand|Select|Wrap|Line Numbers
  1.  if( Console.In.Peek() != -1 )
  2.     {
  3.       Console.WriteLine("GOT STDIN");
  4.       return;
  5.     } 
...it blocks and user must hit return to continue.
Is there a test I can do in C# that will not block?
Thanks
Oct 20 '09 #1
11 12218
tlhintoq
3,525 Expert 2GB
If it were a WinForm app I would suggest reacting to the keypress event.
That way as soon as any key is pressed you can move on to whatever you like.
Does it have to be a console app?
Oct 20 '09 #2
Plater
7,872 Expert 4TB
Does this work?
Console.OpenStandardInput().Length
Oct 20 '09 #3
Thanks for your replies.
> Does it have to be a console app? - reacting to the keypress event
Yes it is just a filter app.

I think you CAN get keypress events in a Console app but
I don't think piped data would cause a keypress event and
the program will not be taking any Q&A user input.
The program will filter a stream of floating point numbers.
I wanted the user to be able to supply the stream either:
- piped in on the command line
. . eg: echo "1.2334 2.345 3.456 " | myprog
- or from a file supplied by user as arg[0]

If neither is supplied the prog will create it's own sample data.

I couldnt get anything out of "Console.OpenStandardInput().Length"
Expand|Select|Wrap|Line Numbers
  1.     //Console.WriteLine("Console.OpenStandardInput().Length= {0}", 
  2.     //                                   Console.OpenStandardInput().Length );
  3.     // exception: The stream does not support seeking (with or without piped data)
  4.  
Here is an example of my novice level and the things I have tried:
Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.Text; // for ReadKey()
  3. using System.IO;   // for StreamReader etc
  4.  
  5. class MyProg
  6. {
  7.   static void Main(string[] args)
  8.   {
  9.     //string s1;
  10.     //int i;
  11.     char c;
  12.  
  13.     Console.WriteLine("-----test-----");
  14.  
  15. /****  So far everything has blocked the same as Console.Read():         ****/
  16.     while( Console.In.Peek() != -1 ) // blocks at first read... 
  17.     {
  18.       //s1 = Console.ReadLine();
  19.       //Console.Write(s1);
  20.  
  21.       //i = Console.Read();
  22.       //Console.Write("{0} ", i);
  23.  
  24.       c = (char)Console.Read();
  25.       Console.Write("{0} ", c);
  26.  
  27.       //c = Console.ReadKey();   // even with:  using System.Text; still gets:
  28.       //     Error: System.Console' does not contain a definition for `ReadKey'
  29.       //Console.Write("{0} ", c);
  30.     }
  31. /****/
  32.  
  33. /****  This works to read stdin but still blocks... * /
  34.     TextReader trIn = Console.In;
  35.     while( trIn.Peek() != -1 )
  36.     {
  37.       //Console.WriteLine("trIn.Length= {0} ", trIn.Length );
  38.       // `System.IO.TextReader' does not contain a definition for `Length'
  39.       c = (char)trIn.Read();
  40.       Console.Write("{0} ", c );
  41.     }
  42.     trIn.close();
  43. / ****/
  44.  
  45. /**** This works to read stdin but still blocks the same:
  46.  
  47.     StreamReader srIn= new StreamReader(Console.OpenStandardInput());
  48.     while( srIn.Peek() != -1 )
  49.     {
  50.       //Console.WriteLine("srIn.Length= {0} ", srIn.Length );
  51.       //  System.IO.StreamReader' does not contain a definition for `Length'
  52.       //  
  53.       c = (char)srIn.Read();
  54.       Console.Write("{0} ", c);
  55.       if(c == 'x') break;  
  56.     }
  57.     srIn.Close();
  58. ****/
  59.  
  60. /****
  61.     if( Console.In )  
  62.       Error: Cannot implicitly convert type `System.Console.In' to `bool'
  63. ****
  64.     if( (bool)Console.In )
  65.       Error: Cannot convert type `System.Console.In' to `bool'
  66. ****
  67.     if( Console.In.Good )  // no member "Good"
  68.       Console.Write("Console.In ");
  69.     else 
  70.       Console.Write("NO Console.In ");
  71. ****/
  72.  
  73.     //Console.WriteLine("Console.In= {0}", Console.In ); 
  74.     // ouptput:  Console.In= System.IO.SynchronizedReader
  75.  
  76.     //Console.WriteLine("Console.OpenStandardInput().Length= {0}", 
  77.     //                                   Console.OpenStandardInput().Length );
  78.     // exception: The stream does not support seeking (with or without piped data)
  79.  
  80.     //Console.WriteLine("Console.In.Length= {0}", Console.In.Length ); 
  81.     // error: System.IO.TextReader' does not contain a definition for `Length'
  82.   }
  83. }
There are so many objects and methods in C# I get lost.
I had thought that this would be doable in C# but maybe not. (I wonder why not)
I guess I'll have to get user to indicate input method as a CL argument.
Thanks for the ideas, Howard
Oct 20 '09 #4
GaryTexmo
1,501 Expert 1GB
Have a look here...
http://www.csharpfriends.com/Forums/...x?PostID=53551

You can check to see if a key is available with Console.KeyAvailable, then you can read it out of the stream at that point.

Does that help any?
Oct 20 '09 #5
So Console.KeyAvailable seems to be set to false if there is no piped data
BUT Surprise! I can't tell if it DOES detect piped data because when the
console is in the graphics mode, any piped data will cause an exception!

I can read from command line from within the program if there is no piped data.!

-> gmcs peek_stdin-2.cs
-> mono peek_stdin-2.exe
-> echo -n "dude" | mono peek_stdin-2.exe

Unhandled Exception: System.IO.IOException: Not a tty.
at System.TermInfoDriver.Init () [0x00000]
at System.TermInfoDriver.Clear () [0x00000]
at System.ConsoleDriver.Clear () [0x00000]
at System.Console.Clear () [0x00000]
at MyProg.Main (System.String[] args) [0x00000]

Here is what I've been testing with:
Expand|Select|Wrap|Line Numbers
  1. using System;
  2.  
  3. class MyProg
  4. {
  5.   static void Main(string[] args)
  6.   {
  7.     char c;
  8.  
  9.     /* So here we start with some graphics mode commands: */
  10.     Console.Clear();
  11.     Console.SetCursorPosition( 0, 0);
  12.     Console.Write("-----test-----\n");
  13.  
  14.     if( Console.KeyAvailable)
  15.     {
  16.       Console.WriteLine("got stdin");
  17.     }
  18.     else
  19.     {
  20.       Console.WriteLine("Don't got stdin");
  21.       while( true ).                         
  22.       {
  23.         c = (char)Console.Read();
  24.         Console.Write("{0} ", c);
  25.         if(c == '\n') break;
  26.       }
  27.     }
  28.     */
  29.     //c = (char)Console.Read();    // hold window open to see output 
  30.   }
  31. }
even a single Console.Clear() will cause the exception!
Oh well. maybe I'm missing something.
Thanks for the sugestion though.
Oct 21 '09 #6
Plater
7,872 Expert 4TB
Console.OpenStandardInput().Length should be 0 unless there is data to be read from the standard input.
Oct 22 '09 #7
That works for you?

#### If I try either this:
int x = (int)Console.OpenStandardInput().Length ;

#### or this
Console.WriteLine("Console.OpenStandardInput().Len gth= {0} ",
Console.OpenStandardInput().Length );

### and run with either this:
-> mono peek_stdin-2.exe

#### or this:
-> echo "Hello" | mono peek_stdin-2.exe

#### I get this each time:
Unhandled Exception: System.NotSupportedException: The stream does not support seeking

-----
I am using mono on linux and compiling with either:

mcs progname.cs
or
gmcs progname.cs

Both build the code with no questions warnings or errors.
Maybe mono is the problem?
Or am I missing something as far as how to use Console.OpenStandardInput().Length?
Oct 22 '09 #8
Plater
7,872 Expert 4TB
You are correct, seems the stdin doesn't support the length.
Console.KeyAvailable worked for me though.
Oct 22 '09 #9
> You are correct, seems the stdin doesn't support the length.
Good, then mono is not the problem.

> Console.KeyAvailable worked for me though.
hmm, and you can pipe data to that without getting an exception?
Are you using Windows?
Oct 23 '09 #10
Plater
7,872 Expert 4TB
Yes I am in windows. I would have thought there would be no difference on this matter in mono.
KeyAvailable seems to be similar to C's kbhit()
Oct 26 '09 #11
KeyAvailable seems to be similar to C's kbhit()
I guess they haven't written it yet...
Oh well, I'll just give that quest up and have the user indicate if data is in stdin or file thruough a command line arg:
Expand|Select|Wrap|Line Numbers
  1.  using System;
  2.  
  3. class myprog
  4. {
  5.   static void Main(string[] args)
  6.   {
  7.     string input;
  8.  
  9.     if(args.Length == 0)
  10.     {
  11.       Console.WriteLine("\n     ***** Error: no arguments supplied *****\n"+
  12.         "Usage:  {0}  filin  \n\n" +
  13.         "...where \"filin\" is an input file name \n"+
  14.         "or '-' if input is to be from keyboard or pipe (|) or redirect (<).",
  15.         Environment.GetCommandLineArgs() );
  16.  
  17.        return;
  18.     }
  19.  
  20.     if(args[0] == "-")
  21.     {
  22.       Console.WriteLine("\nReading data from stdin: ");
  23.       input = Console.ReadLine();
  24.       Console.WriteLine(input);
  25.     }
  26.     else
  27.     {
  28.       Console.WriteLine("sorry , haven't written code for file input yet");
  29.     }
  30.   }
  31. }
  32. /*
  33.  
  34. csprogs>  mcs pipe_detect.cs
  35.  
  36. csprogs>  mono pipe_detect.exe
  37.  
  38.      ***** Error: no arguments supplied *****
  39. Usage:  /mnt/e/csprogs/pipe_detect.exe  filin  
  40.  
  41. ...where "filin" is an input file name 
  42. or '-' if input is to be from keyboard or pipe (|) or redirect (<).
  43.  
  44. -----
  45.  
  46. csprogs>  echo -n "123.5 543.2 456.7 987.4" | mono pipe_detect.exe -
  47.  
  48. Reading data from stdin: 
  49. 123.5 543.2 456.7 987.4
  50.  
  51. -----
  52.  
  53. csprogs>  cat > xfile
  54. 123.5 543.2 456.7 987.4
  55.  
  56. csprogs>   mono pipe_detect.exe - <  xfile
  57.  
  58. Reading data from stdin: 
  59. 123.5 543.2 456.7 987.4
  60.  
  61. -----
  62.  
  63. csprogs>   mono pipe_detect.exe xfile
  64. sorry , haven't written code for file input yet
  65.  
  66. -----:)
  67. */
Thanks for your help.
Oct 28 '09 #12

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: David Bruno | last post by:
Hello, I've made a script that parses emails with attachments. I tested the code using input from a file and everything was parsed correctly. However when I used "php://stdin" and piped emails to...
9
by: It's me | last post by:
Why do I get an "AttributeError: read" message when I do: import sys r=sys.stdin.read() ?? I've tried: r=sys.stdin.read(80)
1
by: barr | last post by:
Hi Can any one help. I am trying to write a python scipt that takes input as args and/or as piped input ( possibly the output of another program). I want to read stdin ( the piped in stuuff...
7
by: Sigfried Manner | last post by:
Hello NG! I have following situation: c-prg | webprg "c-prg" is a small c-programm which reads data from an fastCgi-Server and writes them to stdout. The stdout is piped into webprg....
6
by: chad kline | last post by:
FBSD 4.8/GCC //////// C-CODE: //////// char c; while ( 1 ) {
51
by: moosdau | last post by:
my code: do { printf("please input the dividend and the divisor.\n"); if(!scanf("%d%d",&dend,&dor)) { temp1=1; fflush(stdin); } else
7
by: Will McDonald | last post by:
Hi all. I'm writing a little script that operates on either stdin or a file specified on the command line when run. I'm trying to handle the situation where the script's run without any input...
1
by: asdsd sir | last post by:
Hi!I'm new in Python and i'd like to ask some general questions about stdin,stdout... Firstly... if we type like something like : cat "file.txt"|python somefile.py #somefile.py import sys
2
by: ShawnD | last post by:
I'm having some issues when trying to read input off of a pipe using a python script. I'm trying to process packet data from tcpdump in real-time, so it's a filter that needs to read data while the...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.