开发者

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 fu开发者_StackOverflow社区nction 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.


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.


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


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜