1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 
5 
6 typedef struct _Buffer {
7   char *buff;
8   int  room, used;
9 } Buffer;
10 
11 void InitBuffer (Buffer *b);
12 void AppendToBuffer (Buffer *b, const char *str, int len);
13 void ReadFile (Buffer *buffer, FILE *input);
14 
15 #define INIT_BUFFER_SIZE 10000
16 
17 void
InitBuffer(Buffer * b)18 InitBuffer (Buffer *b)
19 {
20   b->room = INIT_BUFFER_SIZE;
21   b->used = 0;
22   b->buff = (char *)malloc(INIT_BUFFER_SIZE*sizeof(char));
23 }
24 
25 void
AppendToBuffer(Buffer * b,const char * str,int len)26 AppendToBuffer (Buffer *b, const char *str, int len)
27 {
28   while (b->used + len > b->room) {
29     b->buff = (char *)realloc(b->buff, 2*b->room*(sizeof(char)));
30     b->room *= 2;
31   }
32   strncpy(b->buff + b->used, str, len);
33   b->used += len;
34 }
35 
36 void
ReadFile(Buffer * buffer,FILE * input)37 ReadFile (Buffer *buffer, FILE *input)
38 {
39   char       buf[BUFSIZ + 1];
40   int        bytes;
41 
42   buffer->used = 0;
43   while (!feof(input) && (bytes = fread(buf, 1, BUFSIZ, input)) > 0) {
44     AppendToBuffer(buffer, buf, bytes);
45   }
46   AppendToBuffer(buffer, "", 1);
47 }
48 
49 int
main(int argc,char * argv[])50 main(int argc, char *argv[])
51 {
52   char filename[] = "xbug.c";
53   FILE *input;
54   Buffer buffer;
55 
56   InitBuffer(&buffer);
57 
58   if (!freopen (filename, "r", stdin))
59     fprintf(stderr, "cannot open file\n");
60 
61   unsetenv ("LD_LIBRARY_PATH");
62 
63   if (!(input = popen("/bin/cat", "r")))
64     fprintf(stderr, "cannot run \n");
65 
66   ReadFile(&buffer, input);
67   pclose(input);
68 
69   return 0;
70 }
71