Saturday, 21 September 2013

Fun with C++

A simple code to open a file and write something and read from a file...(C++)
But something is wrong here..
Let me know...what it is!!!

Comment below..!!!!

#include<iostream>
#include<sstream>
#include<fstream>
using namespace std;
int main()
{
        fstream fobj;
        string filename = "/home/ferdose/Desktop/file.txt";
        string str;
        fobj.open("filename",ios::in|ios::out);
        if(!fobj) cerr<<"Can't open"<<endl;
        fobj>>str;
        fobj<<"hey"<<endl<<"hello";
        cout<<str;
}

6 comments:

  1. fstream is a class of header file...

    ReplyDelete
  2. fobj.open("filename",ios::in|ios::out);
    oops i dint get this........

    ReplyDelete
    Replies
    1. In C, for opening a file, we write fopen("somt.txt","r")
      Here,
      this is the way of opening a file in C++....

      Delete
    2. oh...
      and fobj>>str..
      here fobj is an object of class fstream...then object accesing a data of main().....
      how come??

      Delete
  3. That is the beauty of C++ handling of files...
    Overloading << and >> operators to function as cin and cout for Files...

    ReplyDelete