Ferguzz
Ferguzz

Reputation: 6087

Printing to file from console

I am writing a program on Linux in C where I cannot use fprintf to print to a file. I can use printf to print in the console though. How can I take the console output and write it to a file.

I tried printf("echo whatever >> file.txt"); but as I suspected it doesn't run.

Thanks

Upvotes: 0

Views: 285

Answers (5)

pmg
pmg

Reputation: 108938

You can freopen the stdout stream.

#include <stdio.h>

int main(void) {
  if (freopen("5688371.txt", "a", stdout) == NULL) {
    /* error */
  }
  printf("Hello, world!\n");
  return 0;
}

Upvotes: 0

Rumple Stiltskin
Rumple Stiltskin

Reputation: 10405

You can freopen or dup2 as follows:

#include <unistd.h>
#include <fcntl.h>
int main(int argc, char *argv[])
{
    int f = open("test.txt", O_CREAT|O_RDWR, 0666);
    dup2(f, 1);
    printf("Hello world\n");
    printf("test\n");
    close(f);
    return 0;
}

Upvotes: 0

user380875
user380875

Reputation: 11

You're trying to get your program to output some text and for the shell evaluate the output as a command.

This is unusual, one would normally separate the responsibilities of generating the text to the program, then let the shell redirect that output to a file:

foo.c contains:

...
printf("whatever");
...

Then run your program and redirect standard output to wherever you like:

$a.out >> file.txt

Upvotes: 1

user418748
user418748

Reputation:

Compile and run your program like that

./program > lala.txt

This will "push" all your printf()'s to lala.txt

Upvotes: 0

TyrantWave
TyrantWave

Reputation: 4673

When running the program, append > file.txt to it should work.

./program > file.txt

IIRC, re-routes the STDOUT to the file.

Upvotes: 2

Related Questions