How to redirect c program output to a file?

I try to redirect the output of program c to a file, even when it generates some errors due to input problems. I can send output but error messages to a file.

Does anyone know how to do this?

+3
source share
4 answers

From the C source code, you can redirect the exits with freopen():

Common outputs:

freopen("myfile.txt", "w", stdout);

Errors:

freopen("myfile_err.txt", "w", stderr);
+7
source

(This answer relates to the bash shell and similar tastes. You did not specify your environment, and this question needs this detail.)

I assume that you know about basic redirection with ">". To also write STDERR in addition to STDOUT, use the following syntax:

command > file-name 2>&1

:

http://en.wikipedia.org/wiki/Standard_streams#Standard_input_.28stdin.29

+3

, . , . , , FILE * stderr (), FILE * stdout ( , ), , , .

C - stdio, freopen, FILE *, fprintf(stderr, "fungus"); -, , stderr .

, unix, dup dup2. .

int fd = open("some_file", O_WRONLY);
dup2(2,fd);
close(fd);

"some_file" stderr . dup2 2 (stderr, FILE * stderr, , freopen(x,y,stderr), FILE *stderr ).

. , , fork, dup2 , , ( 0, 1 2 ), exec, , . ( , exe)

+2

linux . linux.

ls > file.txt

The result of this command will be saved to a file.
, just as you can save the output of the program, as, say, the name of the object file: a, run the following command to save the output in the file:

./a > file.txt
0
source

Source: https://habr.com/ru/post/1766115/


All Articles