narayanpatra
narayanpatra

Reputation: 5691

Transferring output of a program to a file in C

I have written a C program to get all the possible combinations of a string. For example, for abc, it will print abc, bca, acb etc. I want to get this output in a separate file. What function I should use? I don't have any knowledge of file handling in C. If somebody explain me with a small piece of code, I will be very thankful.

Upvotes: 0

Views: 619

Answers (4)

Dipstick
Dipstick

Reputation: 10129

You can use the tee command (available in *nix and cmd.exe) - this allows output to be sent to both the standard output and a named file.

./myProgram | tee myFile.txt

Upvotes: 0

Miserable Variable
Miserable Variable

Reputation: 28752

Been a while since I did this, but IIRC there is a freopen that lets you open a file at given handle. If you open myfile.txt at 1, everything you write to stdout will go there.

Upvotes: 1

Joe
Joe

Reputation: 47609

If you're running it from the command line, you can just redirect stdout to a file. On Bash (Mac / Linux etc):

./myProgram > myFile.txt

or on Windows

myProgram.exe > myFile.txt

Upvotes: 4

Pascal Cuoq
Pascal Cuoq

Reputation: 80276

Using function fopen (and fprintf(f,"…",…); instead of printf("…",…); where f is the FILE* obtained from fopen) should give you that result. You may fclose() your file when you are finished, but it will be done automatically by the OS when the program exits if you don't.

Upvotes: 4

Related Questions