Chat on IRC |
foo = system(bar)
Posted by grandsnafu [send private reply] at September 22, 2001, 02:56:27 AM
Is there a way to put the output of a system command (i.e. date) in a variable? (I'm working in C). There's probably a better way to do this, but I was thinking of just putting the output of 'date +%d', which outputs the day of the month, into a variable day using 'day = system("date +%d")'. That just seems to run 'date +%d' and dump it's output to the screen, and I think that day is just empty. And if you think that the whole running date to get the day thing is a bad idea, feel free to suggest better ones.
Posted by taubz [send private reply] at September 22, 2001, 11:42:37 AM
Use perl.
Seriously, you have to open up a pipe to "date +%d" which redirects date's output to a stream (for lack of knowing what the real word is - file handle?), and then you can read its output from the stream. I've never done that in C though... In your code, day has the exit code of date. - taubz
Posted by lordaerom [send private reply] at September 22, 2001, 04:13:20 PM
I don't think there's a standard C way to do it offhand, but, the way that works for me here with FreeBSD is as follows:
#include <stdio.h> #include <stdlib.h> #define BUFFLEN 1024 int main(int argc, char **argv) { FILE* filed; char buff[BUFFLEN]; if(argc != 2) { printf("Usage: %s command\n", argv[0]); exit(1); } filed = popen(argv[1], "r"); if(filed == NULL) { printf("Error running %s\n", argv[1]); exit(1); } while(!feof(filed)) { if(fgets(buff, BUFFLEN, filed) == NULL) break; printf("%s", buff); } pclose(filed); } bash-2.05$ ./popentest "date +%d" 22 See man popen for more information and fun!
Posted by Psion [send private reply] at September 23, 2001, 07:46:31 PM
That's a pretty standard UNIX way to do it. I bet there are analagous Windows API functions that do the trick as well.
Posted by grandsnafu [send private reply] at September 23, 2001, 10:26:12 PM
Thanks a lot taubz, lordaerom, and Psion. Your input really was helpful.
The test program works and I was able to work the code into my program. All the code is working, but I need to make the int day have the value of buff (from lordaerom's example). buff seems to have a newline at the end, and that's causing things to go a little haywire. So, how do you make the newline go away? taubz : if this was perl things would be a lot easier.
Posted by taubz [send private reply] at September 23, 2001, 11:17:21 PM
You could use strrchr to find the \n if it's at the end. If it is (and it always will be), just replace it with a \000. Then use atoi.
- taubz
Register as a new user | ||||||||