Thread: Redirecting stdout

  1. #1
    Registered User
    Join Date
    Nov 2010

    Redirecting stdout

    I'm trying to write a program able to execute the "date" command, retrieve the date printed on the standard output and then pass it to a variable in the program. Unfortunately my program doesn't work, so can you help me to find a way to create a working program, please?
    The code I've written is the following:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <unistd.h>
    int main(){
    	int fd[2];
    		dup2(fd[1], STDOUT_FILENO);
    		execlp("date", "date", NULL);
    	} else {
    		FILE* stream;
    		char* res;
    		stream = fdopen(fd[0], "r");
    		fscanf(stream, "%s", res);
    		printf("The result is %s\n", res);
    	return 0;
    Thanks in advance for any help!

  2. #2
    Registered User
    Join Date
    Sep 2006
    C has standard functions for getting the date. I suggest you use one of them.

    Put your fork, back down with the spoon!

  3. #3
    Registered User
    Join Date
    May 2009
    freopen - C++ Reference

    Note: I agree with prior post use the C built in time functions to get date.

    Tim S.

  4. #4
    Registered User
    Join Date
    Sep 2007
    Obviously you want to use standard functions to get the date. But for reference...

    Your program isn't working because you're not allocating memory for “res”. You can just make it an array in this case. But if you need to read the output of a program on a POSIX system, you probably just want to use popen().

    With real code, you'd also want to check the return values of functions to make sure they ran successfully.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. redirecting stdout of child process
    By frs in forum Linux Programming
    Replies: 2
    Last Post: 07-25-2010, 07:54 PM
  2. redirecting stdout
    By ichijoji in forum C++ Programming
    Replies: 2
    Last Post: 08-15-2006, 09:20 PM
  3. Problems with switch()
    By duvernais28 in forum C Programming
    Replies: 13
    Last Post: 01-28-2005, 10:42 AM
  4. redirecting stdout to a socket
    By Kinasz in forum Linux Programming
    Replies: 2
    Last Post: 03-25-2004, 08:01 AM
  5. redirecting stdout
    By Draco in forum C Programming
    Replies: 13
    Last Post: 10-11-2003, 12:56 AM