1

I want to get the file size downloaded by wget without actually downloading the file. So I use

wget --spider <url> 2>&1 | grep Length | awk '{print $2}' 

and it works. But now my c program use this shell code by

int result = system("wget .....");

However, system return the exit status code which means result will be 0 instead of giving me the file size. How could I get this file size in my c programming code if I still want to use wget --spider? Thanks in advance!

user2489547
  • 171
  • 1
  • 1
  • 9
  • 1
    you need to capture the stdout of the wget program. See here for another question on the matter http://stackoverflow.com/questions/646241/c-run-a-system-command-and-get-output – gbtimmon Jun 21 '13 at 16:42

1 Answers1

1

You'll want to use the popen() command, which forks off and opens a pipe to a shell. This function takes a char pointer to your command and also a mode. It then returns a pointer to the result of your command. Your code would look something like the following.

 #include <stdio.h>
 #include <stdlib.h>
       int main()
       {
              char *cmd = "wget --spider <url> 2>&1 | grep Length | awk '{print $2}'";
              char buf[128];
              FILE *ptr;

              if ((ptr = popen(cmd, "r")) != NULL){
                      while (fgets(buf, 128, ptr) != NULL)
                              printf("%s", buf);
                      }
                      pclose(ptr);
              }
              return 0;
       }
Optox
  • 600
  • 3
  • 9