Tuesday, July 14, 2009

Easy Question: How do you output a C program to a text file?

So let's say there's a C file named test.c





gcc test.c creates an a.out





how do I make the compilation put test.c's output (the printf's) into a text file?





Thanks for the help!

Easy Question: How do you output a C program to a text file?
OK you need to understand the difference between what a printf() is doing within your code and what the output of a compiler is outputting to the screen.





1) The printf() calls only work when you are running the program you have already compiled and its an executable ie .exe.





If you want the printf output to be placed in a textfile then swap the printf()s for fprintf()s and set up the following.





/* file pointer for text file */


FILE *fp;





/* Open the file for writing */


fp = fopen("example.txt", "w");





print("This goes to the screen\n");


fprintf(fp, "This goes to the file\n");


fclose(fp);





After running the executable a file called example.txt should exist that has the line 'This goes to the file' in it.





2) if you want the output of the compiler then all you would do is pipe it to a file eg





gcc test.c %26gt;%26gt; example.txt





printf()s have nothing to do with the compilation or linking stage.


No comments:

Post a Comment