User Tools

Site Tools


cplusplus:file_processing_examples

This is an old revision of the document!


File processing examples

File writing

Simple example

simple-file-write.cpp
// This program writes data to a file.
#include <iostream>
#include <fstream>
using namespace std;
 
int main()
{
    ofstream outfile;   // instantiate file pointer object
    outfile.open("public_radio.txt");   // associate file with file pointer object
 
    cout << "Writing to the file ... ";
 
    outfile << "KCMP\t" << 89.3 << endl;
    outfile << "KNOW\t" << 91.1 << endl;
    outfile << "KSJN\t" << 99.5 << endl;
    outfile.close();    // close the file!
 
    cout << "Done!" << endl;
 
    return 0;
}

Checking for opening errors

simple-file-write2.cpp
// This program writes data to a file.
// Shows error checking.
#include <iostream>
#include <fstream>
using namespace std;
 
int main()
{
    ofstream outfile;   // instantiate file pointer object
    outfile.open("public_radio.txt");   // associate file with file pointer object
 
    if (!outfile)
        cout << "Error opening file." << endl;
    else
    {
        cout << "Writing to the file ... ";
 
        outfile << "KCMP\t" << 89.3 << endl;
        outfile << "KNOW\t" << 91.1 << endl;
        outfile << "KSJN\t" << 99.5 << endl;
        outfile.close();    // close the file!
 
        cout << "Done!" << endl;
    }
 
    return 0;
}

Filenames must be c_str

simple-file-write3.cpp
// This program writes data to a file.
// Converting string to c_str.
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
 
int main()
{
    ofstream outfile;   // instantiate file pointer object
    string filename;    // used to store filename to save file
 
    // get filename from user
    cout << "Enter the filename to store the file in\n"
         << "> ";
    cin >> filename;
 
    outfile.open(filename);   // associate file with file pointer object
 
    if (!outfile)
        cout << "Error opening file." << endl;
    else
    {
        cout << "Writing to the file ... ";
 
        outfile << "KCMP\t" << 89.3 << endl;
        outfile << "KNOW\t" << 91.1 << endl;
        outfile << "KSJN\t" << 99.5 << endl;
        outfile.close();    // close the file!
 
        cout << "Done!" << endl;
    }
 
    return 0;
}

File reading

cplusplus/file_processing_examples.1362100771.txt.gz · Last modified: 2013/03/01 01:19 by mithat

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki