Thread: howto open a file for writing several times

  1. #1
    Registered User
    Join Date
    Jul 2008
    Location
    Barcelona
    Posts
    41

    howto open a file for writing several times

    Hi,
    I would like to open a file for writing several times. I used append which works, but every time I re-run the program the file grows. What I really want to do is only append after the first time the function has been called. So I tried doing like this.
    Code:
    	ofstream voxel;
    	if (nphases == 0) {
    		ofstream voxel (outname.c_str(), ios::out|ios::binary);
    	}
    	else {
    		ofstream voxel (outname.c_str(), ios::out|ios::binary|ios::app);
    	}
    Where nphases is growing every time the function is called in a loop so I know if it is the first time or not. However this didnt work. I hope I explain myself well enough =) Anybody know a good way to do this?

  2. #2
    Kiss the monkey. CodeMonkey's Avatar
    Join Date
    Sep 2001
    Posts
    937
    I'm not sure what it is that you're doing. For one thing, every 'voxel' in that code snippet refers to a different object. What are you doing to the file in this function?
    "If you tell the truth, you don't have to remember anything"
    -Mark Twain

  3. #3
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    Code:
    ofstream voxel;
    voxel.open(outname.c_str(), ios::binary | (nphases == 0 ? 0 : ios::app));
    (For all o*streams, ios::out is implicit.)
    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

  4. #4
    Registered User
    Join Date
    Jul 2008
    Location
    Barcelona
    Posts
    41
    thanks

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need Help Fixing My C Program. Deals with File I/O
    By Matus in forum C Programming
    Replies: 7
    Last Post: 04-29-2008, 07:51 PM
  2. gcc link external library
    By spank in forum C Programming
    Replies: 6
    Last Post: 08-08-2007, 03:44 PM
  3. Encryption program
    By zeiffelz in forum C Programming
    Replies: 1
    Last Post: 06-15-2005, 03:39 AM