File Processing Example

#include <iostream.h>
#include <fstream.h>
/****************************************************
 File: files.C
 This program creates an output file, writes to it,
 closes the file, opens it again as an input file,
 and reads in the data, and displays it. 
****************************************************/

int main()
{
     ofstream fout; // declare object of output stream
     fout.open("test"); // creates normal output file
     if (!fout) {
          cout << "Error: Cannot open output file. \n";
          return 1;
     }

     fout << "Hello!\n";
     fout << 100 << "  " << hex << 100 << endl;

     fout.close(); //close output file stream
  
     ifstream fin("test"); // open normal input file
     if (!fin) {
          cout << "Error: Cannot open input file\n";
          exit(1);
     }

     char str[80];
     int i;
     
     fin >> str >> i;
     cout << str << "  " << i << endl;

     fin.close(); // close input file stream

     exit(0);
}

Contents of File "test":
Hello!
100  64

Output:
Hello!  100

#include <iostream.h> #include <fstream.h> /**************************************************** File: files1.C This program creates an output file, writes to it, closes the file, opens it again as an input file, and reads in the data, and displays it. The file object is of type fstream ****************************************************/ int main() { fstream f; // declare object of fstream f.open("test1",ios::out | ios::noreplace); // creates normal output file if (!f) { cout << "Error: Cannot open output file. \n"; return 1; } f << "Hello!\n"; f << 100 << " " << hex << 100 << endl; f.close(); // close output file stream f.open("test1", ios::in); if (!f) { cout << "Error: Cannot open input file. \n"; return 1; } char str[80]; int i; f >> str >> i; cout << str << " " << i << endl; f.close(); // close input file stream exit(0); }



Back to Previous Page

Document:
Local Date:
Last Modified On: