Unnamed pipe and streams

Hi guys,

I did some code to experiment with unnamed pipes in C/Linux,
and all went fine using read/write to send pipe content to file:

1
2
3
4
5
char buff[20];
int count = 0;
while( (count = read(fd[0], buff, 20)) > 0){
  write(fileno(outfile), buff, count);
}


Problem came when I tried fgetc/fputc or fgets/fputs to
achieve same transfer. I used fdopen(pipe_fd,"r") to get the pipe stream
for the file functions, but obviously I miss something:

1
2
3
4
int c;
while( (c = fgetc(fdopen(fd[0],"r"))) != EOF){ 
  fputc(c,outfile);
}


// or

1
2
3
4
5
6
7
char buff[200];
while( 1 ){
  char *res = fgets(buff, 200, fdopen(fd[0],"r") );
  if( res != NULL){
    fputs(buff, outfile);
  } else 
      break;
Last edited on
while( (c = fgetc(fdopen(fd[0],"r"))) char *res = fgets(buff, 200, fdopen(fd[0],"r") );

... have you considered the fact that you are creating an arbitrary number of FILE* objects that are never closed or even considered after one use? Maybe that’s a problem?
Last edited on
Thanks for that - you are right!

I thought fdopen() just brings ref stream as opposite of fileno() ...
I guessed as much lol, I’m glad your program was fixed. :)
Topic archived. No new replies allowed.