//////////////////////////////////////////
// //
// Reading and writing textual data //
// //
// You found this at bobobobo's weblog, //
// http://bobobobo.wordpress.com //
// //
// Creation date: Feb 8/08 //
// Last modified: Feb 8/08 //
// //
//////////////////////////////////////////
#include <stdio.h>
#include <stdlib.h>
// How do you write to a file in C/C++?
// Its easy!
int main()
{
///////////////////
// fprintf() - stands for File-PRINT-Formatted.
//
// Say you've got some TEXTUAL data
// you want to print out to a simple
// text file for your program.
//
// You know where to turn to. fprintf() !
//
// There are a few steps we must follow here:
// 1. OPEN FILE TO WRITE TO
// 2. WRITE!
// 3. CLOSE THE FILE.
// 1. In order to write out to a file, you
// first have to OPEN A FILE FOR WRITING.
FILE * outfile = fopen( "shoppingList.txt", "w" ); // open "shoppingList.txt" for "w"RITING
// 'outfile' is now a "file pointer" to
// the file "shoppingList.txt" on disk. outfile
// can ONLY BE WRITTEN TO, because I opened
// the file in a WRITE mode, indicated by
// the "w" as the second argument to fopen()
// Notice when I call fopen()
// A. If "shoppingList.txt" doesn't exist, then
// it will be created.
// B. If "shoppingList.txt" DOES exist, then
// shoppingList.txt's contents are CLEARED OUT
// 2. So, now that the file is open, let's write to it!
fprintf( outfile, "Shopping list:\n" );
fprintf( outfile, " - Blueberries\n" );
fprintf( outfile, " - Raspberries\n" );
fprintf( outfile, " - Granola bars\n" );
fprintf( outfile, " - Beer\n" );
// What if we want to write variable values?
// Easy! Just like printf() works, you use
// the %d, %f, %s to tell fprintf() what types
// of variables its printing.
// fprint an int
int qtips = 5000;
fprintf( outfile, " - %d Qtips\n", qtips );
// fprint a float
float purity = 99.4;
fprintf( outfile, " - Soap that is %.1f%% pure\n", purity );
// 3. DONE, so CLOSE THE FILE!
fclose( outfile );
////////////////////
// HOW DO YOU OPEN A FILE WITHOUT
// OVERWRITING ITS CONTENTS?
//
// 1. OPEN: You open the file using "APPEND" mode.
outfile = fopen( "shoppingList.txt", "a" ); // open "shoppingList.txt" for "a"PPENDING
// 2. PRINT: anything we fprintf() here will automatically be
// tacked onto the end of "shoppingList.txt"
fprintf( outfile, "Don't forget the milk !" );
// 3. CLOSE!
fclose( outfile );
printf("\n\n***************************\n* Part 2 - Reading from a file\n");
system("pause");
////////////////////
// READING FROM A FILE.
//
// Now, we're going to write a bit of code
// to read that file we just wrote to.
// Here's how you do it:
// 1. OPEN FILE FOR READING
// 2. READ!
// 3. CLOSE FILE!
// 1. OPEN:
FILE * readfile = fopen( "shoppingList.txt", "r" ); // open "shoppingList.txt" in "r"EAD mode
char buf[300]; // create a buffer of 300 chars
// to temporarily dump data
// from the file into.
while( !feof( readfile ) )
{
// 2. READ!
// let's read one line at a time
fgets( buf, 300, readfile );
// print out that line we just read in
// to the console so we can see it
printf( "%s", buf );
}
// 3. CLOSE!
fclose( readfile );
printf("\nPart 3 - printing the source of __this__ code file.\n");
system("pause");
//////////////////
// A fairly common interview question comes next.
//
// "Write a C program that prints out
// its own source code when it is
// compiled and run."
//
// The trick here about this question is
// you have to know about the __FILE__ macro.
//
// __FILE__ will be automatically identified
// with a string containing the full path
// of the source file.
printf("\nThe source file for this code is: %s\n", __FILE__ );
FILE * source = fopen( __FILE__, "r" ); // open __this__ file for reading
while( !feof(source) )
{
// print every character in the file
// to the console.
printf( "%c", fgetc( source ) );
}
}
//////////////////
// END NOTES:
//
// Note that there IS a C++ "way" to do file output
// that is "object oriented" provided through
// the 'ofstream' object.
//
// I do NOT recommend you use the ofstream
// class however. WHY? Because its REALLY slow.
// In simple tests I've conducted using a high performance
// counter, ofstream takes TWICE AS LONG to print
// the same stream of characters to disk
// as fprintf() does.
// See
// http://bobobobo.wordpress.com/2008/02/07/speed-tests-fprintf-vs-ofstream-and-fprintf-vs-fwrite/
// for a speed test.)
// OOP is good, but it sometimes has
// a pretty bad performance cost.
Download the Visual Studio 2005 project files hosted by esnips (thanks esnips!)
Refs
fprintf entry @ cplusplus.com
fprintf entry @ cppreference.com
One Comment
Thanks a ton… Thoroughly appreciate the efforts put in, The explanations makes it more easier to understand, for a beginner like me…
Thanku again.