simplest way to write and read text file in c++

This topic contains 5 replies, has 3 voices, and was last updated by  Anonymous 12 years, 7 months ago.

  • Author
    Posts
    1 Star2 Stars3 Stars4 Stars5 Stars Rate it First!
  • #13348
    Member
    Posts: 521

    weekend get bored

    #include
    #include
    #include
    using namespace std;
    
    int _tmain(int argc, _TCHAR* argv[])
    {
    string filename="test.txt";
    string line="hello worldrn";
    fstream ofile(filename.c_str(),
    ios_base::out | ios_base::binary);
    if(!ofile.is_open())
    {
    cout << "Cannot Open " << filename.c_str()
    << " for writingn";
    return 0;
    }
    for(int i=0; i<5; i++) //write 4 lines to file
    ofile.write(line.c_str(), line.length());
    ofile.close();
    return 0;
    }
    
    
    
    and read text file
    
    

    char FileBuffer[256];
    fstream ifile(filename.c_str(),
    ios_base::in | ios_base::binary);
    if(!ifile.is_open())
    {
    cout << "Cannot Open " << filename.c_str()
    << " for readingn";
    return 0;
    }
    while(!ifile.eof())
    {

    ifile.getline(FileBuffer, 256);
    cout << FileBuffer << endl;
    }
    ifile.close();

    seriously I dont use fstream in any of my programm, I use fopen,fread and fwrite. fstream for newbie to c++ 😉

    #28982
    Member
    Posts: 171

    I suggest that you catch the exceptions while writing and reading (it is a must in java now days 🙂 )
    and take a look about CFile at msdn -> http://msdn2.microsoft.com/en-us/library/60fh2b6f(VS.80).aspx
    it is a MFC class

    have fun 🙂

    #28983
    Member
    Posts: 521

    to make it simple the catch exception is avoid for the clarify

    #28984
    Member
    Posts: 4244

    C++ is way above my little mind….im still a VB noob…lol 😀

    #28985
    Member
    Posts: 521

    Me too i’m vb6 noob
    ninja if I were you, I learn c++ first; if you can code in c++ you can code in every programming language

    #28986
    Member
    Posts: 4244

    thanks for that advice man…..that sounds real good 😀

You must be logged in to reply to this topic.