Home arrow C and C+ arrow Streams in C++
Streams in C++ PDF
Tuesday, 19 April 2011
We use streams in C++ to work with files or to print data on the screen.

In order to acomplish that we will use:
- <iostream> library for cout and cin
- <fstream> library for working with files

In the next example we use:
- ifstream is;   - to define the input stream
- is.open(myFile.c_str());   - open() to open the stream, c_str() to convert the C++ string to C string
- is.seekg(0, ios::end); - to go to the end of stream, and is.seekg(0, ios::beg); to go to the beginning counting with is.tellg() the length of the string
- is.read(buff, bufLength); to read from the stream
- cout << buff; to print out the buffer of the content we've read from the file;
- we test with is.fail() if the stream cannot be open.


fstream example: will read stream from file and out put it to screen
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
  ifstream is;
  string myFile="readme.txt";
  int bufLength;
  char *buff;

  is.open(myFile.c_str());

  if (is.fail())
        return -1;

  is.seekg(0, ios::end);
  bufLength = is.tellg();
  is.seekg(0, ios::beg);

  buff = new char[bufLength];

  is.read(buff, bufLength);
  cout << buff;

  is.close();

  delete[] buff;
  return 0;
}



Last Updated ( Tuesday, 03 May 2011 )
 
< Prev   Next >

Other BSD Systems

OpenBSD

Misc

Solaris

Polls

Best BSD firewall?