Output to File
2002-01-31 16:15:10
Category: cpp:files
Description: Shows how to write text to a file in c++ using append or normal out
Author: detour
Viewed: 3770
Rating: (10 votes)


/* outfile.cpp by detour@metalshell.com
 *
 * Simple example of writing text to a file, by
 * using append or standard out.
 *
 * http://www.metalshell.com/
 */
 
#include <iostream>
#include <fstream.h>
 
/* for append type = 1
   for normal out type = 0 */
 
#define type 0
 
int main() {
    char outLine[50];
 
    ofstream outFile;
    /* open the file */
    if(type)
        outFile.open("output.txt", ios::app);
    else
        outFile.open("output.txt", ios::out);
 
    /* if opening didn't fail */
    if(!outFile.fail()) {
        cout << "Enter some text: ";
        cin >> outLine;
 
        /* write the text to the file */
        outFile << outLine << endl;
        outFile.close();
    } else 
        cout << "Error Opening File.";
 
    return 0;
}