Tuesday, 27 March 2012

The fprintf Function in C & C++


You can open a text or binary file with fopen and close it with fclose. (See here.) The fprintf function allows you to “print” data to a text file. It is similar to the printf function except the output goes to a file instead of the standard output.

A note on text files versus binary files. If you open a text file with an editor program, chances are you can read and make some sense of what’s there. Not so with a binary file. The binary file is raw data in the way variables stored in memory are raw data—binary data. But text files store binary data as well, but along the way, it’s converted to a human readable form using an ASCII table or Unicode character set. So while you may write “Hello World” to a text file and see it as such, it is being converted to some binary code.

Back to the fprintf function. The same code explains it.

Test Code.

I tested the functions in Visual C++ 2010 as an console application.

// The standard library includes the system function.
#include <cstdlib>

// C++ standard I/O library.
#include <cstdio>

int main()
{
     // Header.
     printf("\"Print\" Data To A Text File\n\n");

     // Pointer to the file.
     FILE* pFileHandle;

     // Puts the file in the project path.
     char Filename[] = "MyFile.txt";

     // Version 1.
     // w attribute for writing to the file.
     // If the file does not exist, it is created.
     // Any existing file content is overwritten.
     printf("File attribute: w - (over) write\n");
     pFileHandle = fopen(Filename, "w");

     // Write data to file.
     fprintf(pFileHandle , "\"Print\" Data To A Text File\n\n");
     fprintf(pFileHandle , "Writing some data to a text file.\n");
     fprintf(pFileHandle , "Any existing data in the file is lost.\n");

     // Close the file.
     int iReturn = 0;
     iReturn = fclose(pFileHandle);

     // Version 2.
     // a attribute for appending to the file.
     // If the file does not exist, it is created.
     // Any existing file content remains.
     printf("File attribute: a - appending\n");
     pFileHandle = fopen(Filename, "a");
     // Write data to file.
     fprintf(pFileHandle , "With appending mode, text is added to the file.\n");

     // Close the file.
     iReturn = fclose(pFileHandle);

     // Version 3.
     // What happens when you try to write data to a file opened for reading.
     printf("File attribute: r - reading\n");
     pFileHandle = fopen(Filename, "r");
     // Write data to file.
     fprintf(pFileHandle , "With reading mode, text isn't added to the file.\n");
     // There is no run-time error or compile error.

     // Close the file.
     iReturn = fclose(pFileHandle);

     // Keep console window open.
     system("pause");

     // Return some value.
     return 0;
} // end main


Text File.


No comments:

Post a Comment