Problem with pipes.

I'm making a program to generate the sequence of numbers:
1
11
21
1211
111221

To do this I had the stupid idea of using pipes to output the sequence back at my program, thus avoiding memory allocation. However it seems that at the 40th term the program hangs waiting for input from itself, indicating that the writes of the 39th term didn't all go through the pipe. Does anyone have a clue why this could be?
Here's my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include "stdio.h"
#include "unistd.h"
#include "string.h"

int main(int argc,char **argv){
	FILE *nin,*nout;
	int terms=10,len=1,no;
	{
		int fildes[2];
		pipe(fildes); /*Make a pipe to avoid having my own buffer*/
		nin=fdopen(fildes[0],"r");
		nout=fdopen(fildes[1],"a");
	}
	if(argc>1)sscanf(argv[1],"%d",&terms);
	if(argc>2){
		fputs(argv[2],nout);
		len=strlen(argv[2]);
		fflush(nout);
	}else{
		fputs("1",nout);
		puts("1");
		fflush(nout);
	}
	for(no=0;no<terms;no++){
		printf("#%d %dn",no,len);
		int ctr=0,newlen=0,actr=0,achr=0;
		while(ctr<len){
			int c=fgetc(nin);
			ctr++;//counting characters until the end of this term.
			if(achr==0){
				actr=1;
				achr=c;
			}else if(achr!=c){//on the first differing character,
				int n;
				fprintf(nout,"%d%c%n",actr,achr,&n);//output the length of the sequence and the character itself.
				fflush(nout);
				printf("%d%c",actr,achr,);
				newlen+=n;
				actr=1;
				achr=c;
			}else actr++;
		}
		int n;
		fprintf(nout,"%d%c%n",actr,achr,&n);
		fflush(nout);
		printf("%d%cn",actr,achr);
		newlen+=n;
		len=newlen;
	}
	return 0;
}
Topic archived. No new replies allowed.