Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

Printing to a Text File in C

Posted on 2009-04-19
3
Medium Priority
?
253 Views
Last Modified: 2012-05-06
I need to print to a text file rather than on the screen.  Below is my code that prints it to the screen, but I need it to print to a text file.  How would I change the print statement?

  for (i = 0 ; i <= last ; i++) /* when the sort is complete, write to output file */
          printf("%s\n",name[i]) ;
0
Comment
Question by:clscor2
  • 2
3 Comments
 
LVL 40

Expert Comment

by:evilrix
ID: 24179657
Open a file using fopen and then use fprintf rather than printf to print to that handle.

FILE fp = fopen("filename.txt", "w");

if(fp)
{

  for (i = 0 ; i <= last ; i++) /* when the sort is complete, write to output file */
            fprintf(fp, "%s\n",name[i]) ;

}

http://www.cplusplus.com/reference/clibrary/cstdio/fprintf/
http://www.cplusplus.com/reference/clibrary/cstdio/fopen/
0
 
LVL 40

Accepted Solution

by:
evilrix earned 200 total points
ID: 24179687
Oops.... just spotted a typo...

FILE * fp = fopen("filename.txt", "w");

Notice that fp should be a pointer :)
FILE * fp = fopen("filename.txt", "w");
 
if(fp)
{
 
	for (i = 0 ; i <= last ; i++) /* when the sort is complete, write to output file */
		fprintf(fp, "%s\n",name[i]) ;
 
}

Open in new window

0
 

Author Closing Comment

by:clscor2
ID: 31571989
Thank you!  This works perfectly!!!
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
The goal of this video is to provide viewers with basic examples to understand and use structures in the C programming language.
The goal of this video is to provide viewers with basic examples to understand recursion in the C programming language.

577 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question