Gold University of Minnesota M. Skip to main content.University of Minnesota. Home page.
 
 
 

What's inside.

Ta Email

Download Compiler

Final Project

Lab Notes

Office Hours

Schedule

Syllabus

Announcements

Check Grades

 

CSci 1113 Home

 
 

Printer-friendly version

 
File I/O Examples

1. Write to a file

% cat fileEx1.cpp
// file i/o example - write to a file
#include<iostream>
#include<fstream>
using namespace std;

int main()
{
  // create an output file
 
 ofstream file_out;
 file_out.open( "testfile");

 if( file_out.fail() ) // check for successful open
 {
    cout << "File was not successfully opened " << endl;
    exit(1);
 }

 int num1 = 777, num2 = 888;

 file_out << num1 << " " << num2 << " ";

 return 0;
}


% g++ fileEx1.cpp
% a.out
% cat testfile
777 888



2. Read from a file

% cat fileEx2.cpp
// file i/o example - read from a file
#include<iostream>
#include<fstream>
using namespace std;

int main()
{

 // open an input file
 
 ifstream file_in;
 file_in.open( "testfile" );

 if( file_in.fail() ) // check for successful open
 {
    cout << "File was not successfully opened " << endl;
    exit(1);
 }

 int i1, i2;

 file_in >> i1 >> i2;

 cout << "Data read: " << i1 << "  " << i2 << endl;

 return 0;

}
% g++ fileEx2.cpp
% a.out
Data read: 777  888
 

3. Append to a file

% cat fileEx1.cpp
// file i/o example - add to a file
#include<iostream>
#include<fstream>
using namespace std;

int main()
{
  // create an output file
 
 ofstream file_out;
 file_out.open( "testfile", ios::app); // append

 if( file_out.fail() ) // check for successful open
 {
    cout << "File was not successfully opened " << endl;
    exit(1);
 }

 int num1 = 123, num2 = 456;

 file_out << num1 << " " << num2 << " ";

 return 0;
}

% g++ fileEx1.cpp
% a.out
% cat testfile
777 888 123 456


 
The University of Minnesota is an equal opportunity educator and employer.
CSci 1113: C++ Programming