Slide 1.12: Hashing
Slide 2.2: Opening and closing files (cont.)
Home

Opening and Closing Files


When the word “file” is referred, it implies either one of the two meanings: Before the program can open a file for use, the operating system must receive instructions about making a hookup between a logical file and some physical file or device.

A Program Example
The program below shows how to create and write to a file:
  1. Creates a text file named test.txt located in the local directory, where the program is stored.
  2. The text “This is only a test.” is written on it by using the insertion operator <<.
  3. List the contents of the file test.txt by using the Unix command cat.
  4. Display the text “The file test.txt is created.” on the standard output.
Opening and Closing Files            
#include <fstream>
#include <iostream>
#include <cstdlib>
  using namespace std;

int  main( ) {
  fstream  file;

  file.open( "test.txt", fstream::out );
  file << "<br>This is only a test.<br>";
  file.close( );
  system( "cat test.txt" );
  cout << "<br>The file <em>test.txt</em> is created.";
}