user902691
user902691

Reputation: 1159

Redericting stdout and stdin

I would like to redericting stdout, stderr to file and stdin from char*. My goal is make it in C.

When i run this code:

int main(){
        stdout=fopen("/home/user/file.txt","w");
    printf("aaaa");
    printf("\nbbbb");
    system("/bin/bash");
    sprintf("stdin","exit");
    return 0;
}

File didn't have for some string and bash take argument from console. Where is bug??

Upvotes: 1

Views: 392

Answers (3)

BLUEPIXY
BLUEPIXY

Reputation: 40145

#include <stdio.h>
#include <stdlib.h>
#include <io.h>

int main(void){
    int ret;
    FILE *fp;
    int  stdout_bk;

    stdout_bk = dup(fileno(stdout));
    fp=fopen("/home/user/file.txt","w");
    dup2(fileno(fp), fileno(stdout));
    ret = system("/bin/bash");
    //flushall();//for vc
    fflush(stdout);//for gcc 
    fclose(fp);

    dup2(stdout_bk, fileno(stdout));//restore

    return 0;
}

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490008

You don't want to assign to stdout. Instead, you (probably) want to use freopen, in your case like: freopen("/home/user/file.txt","w", stdout);

If/when you're doing all the processing internally, you're generally better off writing the code to receive a FILE * as a parameter, and passing the correct value. That doesn't work when you have external code that writes directly to stdout though.

Edit: I should probably also mention one other serious problem with freopen -- no method is provided to restore it to the previous stream. It's up t you to use freopen again, and know the path that will write to the console (or whatever).

Upvotes: 3

Chris Browne
Chris Browne

Reputation: 1612

stdout should not be used as an lvalue. Try the fprintf() function instead of printf() to get the desired effect.

As for redirecting the stdout from bash, can you not just call it with /usr/bin/bash >> /home/user/file.txt?

Upvotes: 1

Related Questions