Thread: Appending to a text file

  1. #1
    Dr Dipshi++ mike_g's Avatar
    Join Date
    Oct 2006
    Location
    On me hyperplane
    Posts
    1,218

    Appending to a text file

    Heres a function thats intended to append a string to a text file:
    Code:
    bool FString::Append(const char* filename)
    {
    	ofstream out;
    	out.open(filename);
    	if(!out.is_open())return false;
    	
    	out.seekp(0, ios::end);
    
    	out.write(str_ptr, (int)strlen(str_ptr));
    	return true;
    }
    I want it to seek the end of the file then write from there on, which I thought I was doing with seekp(). The problem is it overwrites the contents of the file. What am I doing wrong here?

    Cheers.

  2. #2
    Registered User
    Join Date
    May 2006
    Posts
    903
    Code:
    out.open(filename, ios::app);

  3. #3
    Dr Dipshi++ mike_g's Avatar
    Join Date
    Oct 2006
    Location
    On me hyperplane
    Posts
    1,218
    Thanks that works, and I don't even need the seekp() anymore. Oh and I added out.close() at the end before anyone points that out. Cheers

  4. #4
    Registered User
    Join Date
    May 2006
    Posts
    903
    I'd do this instead though:

    Code:
    bool Append(const std::string& filename)
    {
    	std::ofstream out(filename.c_str(), std::ios::app);
    	if(out.is_open( ))
    	{
    		out << str;
    		return true;
    	}
    	return false;
    }
    Considering that I changed str_ptr (char*) to str (std::string).

    Edit: It's a bit more C++ ish and I find it much cleaner.

  5. #5
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    The explicit close() is not necessary. That's the nice thing about RAII.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  6. #6
    Dr Dipshi++ mike_g's Avatar
    Join Date
    Oct 2006
    Location
    On me hyperplane
    Posts
    1,218
    Thanks for the tips.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Newbie homework help
    By fossage in forum C Programming
    Replies: 3
    Last Post: 04-30-2009, 04:27 PM
  2. Can we have vector of vector?
    By ketu1 in forum C++ Programming
    Replies: 24
    Last Post: 01-03-2008, 05:02 AM
  3. Inventory records
    By jsbeckton in forum C Programming
    Replies: 23
    Last Post: 06-28-2007, 04:14 AM
  4. How to use FTP?
    By maxorator in forum C++ Programming
    Replies: 8
    Last Post: 11-04-2005, 03:17 PM
  5. Outputting String arrays in windows
    By Xterria in forum Game Programming
    Replies: 11
    Last Post: 11-13-2001, 07:35 PM