tags:

views:

81

answers:

4

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.

+4  A: 

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.

Pascal Cuoq
Correct. I'd do the same.
mingos
Means I have to create or open a file through my code?Let me check the syntax of fopen and fprintf. Thanks for the help.
+4  A: 

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
Joe
Actually, on windows it's the same as in Linux. You need a `>`, not a `|`
Nathan Fellman
It is *still* `myProgram.exe > myFile.txt` in cmd.exe.
KennyTM
Yes, corrected thanks. It's been a few years!
Joe
Good one, although not as obvious to Windows users. I must say I didn't think about it initially either (my contact with Linux is limited as I usually only turn it on to efence a nasty segfault).
mingos
thanks for suggestion but I have to use the output in the same program. So it won't work for me.
That's fine. For many UNIX programs, the philosophy is take a standard-in stream and a standard-out stream and rely on the process calling the program to take input and direct output as required. You may find some of your programs in the future fit this description. This one doesn't, but it's good to have at the back of your mind.
Joe
+1  A: 

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.

Hemal Pandya
Or you can do something like: stdout = fopen("file", "w");
mathepic
@mathepic Maybe you "can", but you shouldn't: "The primary use of the freopen function is to change the file associated with a standard text stream (stderr, stdin, or stdout), as **those identifiers need not be modifiable lvalues to which the value returned by the fopen function may be assigned**." (footnote 232 in the C99 specification, emphasis mine)
Pascal Cuoq
Ahh, good point. I only use it when using Bison to redirect the input of yyparse... I guess I should do this instead.
mathepic
A: 

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
Dipstick