Redirecting stdout

This is a discussion on Redirecting stdout within the C Programming forums, part of the General Programming Boards category; Hello! I'm trying to write a program able to execute the "date" command, retrieve the date printed on the standard ...

  1. #1
    Registered User
    Join Date
    Nov 2010
    Posts
    12

    Redirecting stdout

    Hello!
    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:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <unistd.h>
    
    int main(){
    
    	int fd[2];
    
    	pipe(fd);
    
    	if(!fork()){
    
    		close(fd[0]);
    		dup2(fd[1], STDOUT_FILENO);
    		execlp("date", "date", NULL);
    
    	} else {
    
    		FILE* stream;
    		char* res;
    
    		close(fd[1]);
    		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
    Posts
    8,868
    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
    Posts
    2,553
    freopen - C++ Reference

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

    Tim S.

  4. #4
    cas
    cas is offline
    Registered User
    Join Date
    Sep 2007
    Posts
    982
    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, 09:42 AM
  4. redirecting stdout to a socket
    By Kinasz in forum Linux Programming
    Replies: 2
    Last Post: 03-25-2004, 07:01 AM
  5. redirecting stdout
    By Draco in forum C Programming
    Replies: 13
    Last Post: 10-11-2003, 12:56 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21