Use get() and getline() to read characters. : File Read Write « File « C++






Use get() and getline() to read characters.

  
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
  char ch;
  char str[256];

  ofstream fout("test.dat");
  if(!fout) {
    cout << "Cannot open file for output.\n";
    return 1;
  }

  fout << "This is a line of text.\n";
  fout << "This is another line of text.\n";
  fout << "This is the last line of text.\n";

  fout.close();
  if(!fout.good()) {
    cout << "An error occurred when writing to the file.\n";
    return 1;
  }

  ifstream fin("test.dat", ios::in);
  if(!fin) {
    cout << "Cannot open file for input.\n";
    return 1;
  }

  cout << "Use get():\n";

  cout << "Here are the first three characters: ";
  for(int i=0; i < 3; ++i) {
    fin.get(ch);
    cout << ch;
  }
  cout << endl;

  fin.get(str, 255);
  cout << "Here is the rest of the first line: ";
  cout << str << endl;

  fin.get(ch);

  cout << "\nNow use getline():\n";

  fin.getline(str, 255);
  cout << str << endl;
  fin.getline(str, 255);
  cout << str;

  fin.close();
  if(!fin.good()) {
    cout << "Error occurred while reading or closing the file.\n";
    return 1;
  }

  return 0;
}
  
    
  








Related examples in the same category

1.Reads information from the file and outputs it onto the screenReads information from the file and outputs it onto the screen
2.Another example of read() and write() and illustrates the use of gcount( )Another example of read() and write() and illustrates the use of gcount( )
3.Opening Files for Read and Write
4.read( ), write( ) and gcount( ):