Reading from and writing to same file

This is a discussion on Reading from and writing to same file within the C++ Programming forums, part of the General Programming Boards category; okay, hopefully this'll be my last question for the day. I got the hard part of my program done Basically ...

  1. #1
    Registered User
    Join Date
    Jan 2005
    Posts
    46

    Reading from and writing to same file

    okay, hopefully this'll be my last question for the day. I got the hard part of my program done

    Basically I'm writing a program that manages a database for a library. it's a data file in this format:

    Title
    Author
    # of copies
    Price (in dd.cc form)

    what I need to do is be able to add a book to the database without overwriting. so I have two questions:

    1) if I simply output the new book to the file will it overwrite the old one?
    2) is there a way to send the cursor to the bottom of the file so it starts writing there without using getline?

    sorry for starting so many threads today, but I need to get this done

  2. #2
    Slave MadCow257's Avatar
    Join Date
    Jan 2005
    Posts
    735
    read this fstream tutorial
    http://www.daniweb.com/techtalkforum...2&page=1&pp=15
    it will answer your questions

    2) is there a way to send the cursor to the bottom of the file so it starts writing there without using getline?
    Yes, open the file with the flag ios::app

  3. #3
    Magically delicious LuckY's Avatar
    Join Date
    Oct 2001
    Posts
    856
    Code:
    #include <iostream>
    #include <fstream>
    using namespace std;
    
    bool addRec(DBRec *pRec) {
      // open an output stream
      // in binary mode
      // and initialize it with the file pointer ready to append
      ofstream fout("your.db", ios_base::out | ios_base::binary | ios_base::app);
    
      if (!fout.is_open()) {
        fout.write((const char*)pRec, sizeof(DBRec));
        fout.close();
        return true;
      }
      
      return false;
    }
    Also note that you should not use getline() for binary files (but come to think of it, you might be writing records in text mode, in which case ignore the binary part of my example).

    [edit]
    You might want to look up the following functions:
    Code:
    seekg();// move the file pointer
    tellg();// returns the current index of the file pointer
    seekp();// move the file pointer
    tellp();// returns the current index of the file pointer
    /* ...g() = input stream, ...p() = output stream */
    [/edit]
    Last edited by LuckY; 02-01-2005 at 03:43 PM.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21