Thread: trouble writing a text file

  1. #1
    Registered User
    Join Date
    Jan 2011

    trouble writing a text file

    I am writing a text file which has the number of records in it at the start and then each record is stored at a 400 boundary - or rather should be!

    In the following snippet the number of records is being updated and recorded at the start of the file OK but the string I am writing should be at 400, 800, 1200 etc but this part is not working, when I inspect the file there is only the one string and it's position varies only a little.

    I am sure it must be an incorrect setting but I have tried all the ios::beg etc but none seem to make a difference

            jcin.close ();
            cout<<endl<<endl<<endl<<"There are currently "<<numrecords<<" records in this file.";
            ofstream jcout;
  , ios::out);
            long int pos;
            jcout.seekp (pos);
            jcout<<"hello sailor";//will be replace by a record
            cout<<endl<<"position is ; "<<pos<<endl;
            jcout.seekp (0);
            jcout<<numrecords++;//this is updating correctly
            jcout.close ();

  2. #2
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    I believe that this
    ofstream jcout;, ios::out);
    will essentially truncate the file. Try an fstream instead of an ofstream. I believe it defaults to in/out mode, so it won't truncate.
        fstream jcout(filename);
    The cost of software maintenance increases with the square of the programmer's creativity. - Robert D. Bliss

  3. #3
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    United States
    I gave up long ago trying to understand what the default behavior of the objects were. You can just mask together features you want with the pipe operator. A list of features is here: ios_base::openmode - C++ Reference.
    ofstream jcout; (filename, ios::out | ios::app);
    I still think it's good to use ofstream and ifstream though, unless you want to read and write from the same stream.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Trouble Writing To File
    By NuNn in forum C Programming
    Replies: 2
    Last Post: 03-23-2009, 09:44 AM
  2. Trouble writing to file using fwrite()
    By yougene in forum C Programming
    Replies: 4
    Last Post: 12-30-2008, 05:13 PM
  3. Trouble writing characters to a file.
    By themusician31 in forum C Programming
    Replies: 7
    Last Post: 08-10-2008, 05:50 AM
  4. trouble with text file reading/writing
    By sbeehre in forum C Programming
    Replies: 25
    Last Post: 08-02-2006, 09:48 PM
  5. Trouble writing to file
    By Fyodorox in forum C++ Programming
    Replies: 7
    Last Post: 05-06-2002, 06:09 PM