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

Viewing 6 posts - 1 through 6 (of 6 total)
  • Author
    Posts
  • #191290

    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++ 😉

    #191295
    Dody
    Member

    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 ->
    it is a MFC class

    have fun 🙂

    #191294

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

    #191293
    Admin
    Administrator

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

    #191292

    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

    #191291
    Admin
    Administrator

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

Viewing 6 posts - 1 through 6 (of 6 total)
  • You must be logged in to reply to this topic.