Back to index

glibc  2.9
xbug.c
Go to the documentation of this file.
00001 #include <stdio.h>
00002 #include <stdlib.h>
00003 #include <string.h>
00004 
00005 
00006 typedef struct _Buffer {
00007   char *buff;
00008   int  room, used;
00009 } Buffer;
00010 
00011 #if __STDC__ - 0
00012 void InitBuffer (Buffer *b);
00013 void AppendToBuffer (register Buffer *b, const char *str, register int len);
00014 void ReadFile (register Buffer *buffer, FILE *input);
00015 #endif
00016 
00017 #define INIT_BUFFER_SIZE 10000
00018 
00019 void InitBuffer(b)
00020      Buffer *b;
00021 {
00022   b->room = INIT_BUFFER_SIZE;
00023   b->used = 0;
00024   b->buff = (char *)malloc(INIT_BUFFER_SIZE*sizeof(char));
00025 }
00026 
00027 void AppendToBuffer(b, str, len)
00028      register Buffer *b;
00029      const char *str;
00030      register int len;
00031 {
00032   while (b->used + len > b->room) {
00033     b->buff = (char *)realloc(b->buff, 2*b->room*(sizeof(char)));
00034     b->room *= 2;
00035   }
00036   strncpy(b->buff + b->used, str, len);
00037   b->used += len;
00038 }
00039 
00040 void ReadFile(buffer, input)
00041      register Buffer *buffer;
00042      FILE *input;
00043 {
00044   char       buf[BUFSIZ + 1];
00045   register int        bytes;
00046 
00047   buffer->used = 0;
00048   while (!feof(input) && (bytes = fread(buf, 1, BUFSIZ, input)) > 0) {
00049     AppendToBuffer(buffer, buf, bytes);
00050   }
00051   AppendToBuffer(buffer, "", 1);
00052 }
00053 
00054 int
00055 main(int argc, char *argv[])
00056 {
00057   char filename[] = "xbug.c";
00058   FILE *input;
00059   Buffer buffer;
00060 
00061   InitBuffer(&buffer);
00062 
00063   if (!freopen (filename, "r", stdin))
00064     fprintf(stderr, "cannot open file\n");
00065 
00066   unsetenv ("LD_LIBRARY_PATH");
00067 
00068   if (!(input = popen("/bin/cat", "r")))
00069     fprintf(stderr, "cannot run \n");
00070 
00071   ReadFile(&buffer, input);
00072   pclose(input);
00073 
00074   return 0;
00075 }