0
votes

Say I run a program which makes several printf statements over the course of its running. Naturally every time it hits a printf command it will print. How would I go about instead of printing it, "store" it, and then at the end of the program, take all the lines that should have been printed, sort it AND THEN print it.

e.g.

Run Program
prints "File1 90"
prints "File2 30"
prints "File3 40"
End Program

Run Program
prints "File1 90" (don't actually print it out)
prints "File2 30" (don't actually print it out)
prints "File3 40" (don't actually print it out)
Take print statements and rearrange them by numerical order, then print
Program prints:
prints "File2 30"
prints "File3 40"
prints "File1 90"

I think I have to use a unix shell command within my C program such as sort -k2n,2 -k1,1 myprogram

1
Do you want the program to sort its own output? Is there any reason you couldn't just pipe the output through sort?templatetypedef
Yup, this ^. You have all the tools you need for the job on unix. Just use it.nullpotent
How would I do that within the program? I realize that I could pipe the output through sort, but how would I do that within the program so its not a command I have to type in afterwardsLocke McDonnell
you wrap your program in a script, that has a command line like myProgram arg1 file [file ...n] | sort. Good luck.shellter

1 Answers

1
votes

One way I can think of is to redirect the stdout to file

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

and then feed the file to sort with -k 2 arguments, since you want to sort on second column (?)

And as for the command/s refer to this example.

It ilustrates the basics.