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.
views:
81answers:
4
+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
2010-08-22 11:16:39
Correct. I'd do the same.
mingos
2010-08-22 11:20:11
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.
2010-08-22 11:23:31
+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
2010-08-22 11:17:11
Actually, on windows it's the same as in Linux. You need a `>`, not a `|`
Nathan Fellman
2010-08-22 11:18:24
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
2010-08-22 11:22:30
thanks for suggestion but I have to use the output in the same program. So it won't work for me.
2010-08-22 11:25:47
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
2010-08-22 11:38:59
+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
2010-08-22 11:36:02
@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
2010-08-22 14:04:20
Ahh, good point. I only use it when using Bison to redirect the input of yyparse... I guess I should do this instead.
mathepic
2010-08-22 14:09:57
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
2010-08-22 12:08:33