HOWTO reading pipe from /dev/stdin

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • horvatj
    New Member
    • Aug 2007
    • 2

    HOWTO reading pipe from /dev/stdin

    Dear c/c++ people,

    What I'm trying to do is something like that:

    # wget http://server.com/my_mpeg_stream. mp4 | myprog -

    so I can use my program (myprog), which is able to decode mp4 streams (file based only at the moment) , for decoding web streams as well.

    Can someone tell me how to read from stdin, as it would be a mp4 file?

    Or is there even a better solution?

    Thanks Johann
  • RRick
    Recognized Expert Contributor
    • Feb 2007
    • 463

    #2
    stdin can be treated like a FILE * so you can use any of the C based IO functions.

    You just need to be careful and not use functions that stdin doesn't work with (i.e. fwrite). Fread, fgetc, etc. should work fine. I'm not sure if fseek and the file positioning functions will work or not.

    Comment

    • horvatj
      New Member
      • Aug 2007
      • 2

      #3
      Thanks, here's my code to share:

      Code:
      #include <stdio.h>
      #include <stdlib.h>
      
      #define BUFFERSIZE	1
      
      int main(int argc, char **argv){
      	unsigned char 	buffer[BUFFERSIZE];
      	FILE 						*instream;
      	int							bytes_read=0;
      	int							buffer_size=0;
      	
      	
      	buffer_size=sizeof(unsigned char)*BUFFERSIZE;
      	/* open stdin for reading */
      	instream=fopen("/dev/stdin","r");
      	
      	/* did it open? */
      	if(instream!=NULL){
      		/* read from stdin until it's end */
      		while((bytes_read=fread(&buffer, buffer_size, 1, instream))==buffer_size){
      			fprintf(stdout, "%c", buffer[0]);
      		}
      	}
      	/* if any error occured, exit with an error message */
      	else{
      		fprintf(stderr, "ERROR opening stdin. aborting.\n");
      		exit(1);
      	}
      	
      	return(0);
      }
      now you may use it like this
      Code:
      # cat somefile.txt | thisprog

      Comment

      Working...