title: C Language: popen() with fread()?
body: <p>I've been stuck on this for a few days and it's getting really frustrating.  </p>
  
  <p>I'm using <code>popen()</code> to call a command line process and get its output and store it in a C string.  I was using <code>fgets()</code> but it seems that breaks after a new line, so I'm using <code>fread()</code>.  The only problem is that the returned C string is sometimes messed up.  </p>
  
  <p>Here's my code:</p>
  
  <pre><code>const char *cmd = "date";//This the shell command
  char buf[BUFSIZ];//Output of the command
  FILE *ptr;
  int c;
  
  if ((ptr = popen(cmd, "r")) != NULL)
       while(fread(buf, sizeof(buf),1, ptr))
            while ((c = getchar()) != EOF)
                 printf("output = %s", buf);
  
  (void) pclose(ptr);
  </code></pre>
  
  <p>The final C string sometimes has weird characters in it that shouldn't be there, or sometimes no string is even available.  Can anybody please help? ):</p>
  
  <p>Edit:  Here is what I was doing when using fgets()  The Shell command can be anything that outputs text though.  Not just "date."</p>
  
  <p><br/><code> if ((ptr = popen(cmd, "r")) != NULL)<br/>while (fgets(buf, BUFSIZ, ptr) != NULL)<br/>printf("output = %s", buf);<br/>(void) pclose(ptr);</code></p>