Thread: Does ofstream::open create the file if it doesn't already exist?

  1. #1
    Programming Ninja In-T...
    Join Date
    May 2009
    Posts
    827

    Question Does ofstream::open create the file if it doesn't already exist?

    Will ofstream:pen(filename) create the file with filename if the said file does not already exist?

  2. #2
    Registered User jeffcobb's Avatar
    Join Date
    Dec 2009
    Location
    Henderson, NV
    Posts
    875
    ofstream:pen(filename) will create the file if it does not exist. If it does exist, what it does after open WRT the file ptr is dictated by the additional ios::XXX flags you pass in like:

    Code:
    ofstream::open(filename, ios::app);
    will open it in append mode...

    open - C++ Reference

    Check out the link for the other permutations..
    C/C++ Environment: GNU CC/Emacs
    Make system: CMake
    Debuggers: Valgrind/GDB

  3. #3
    Programming Ninja In-T...
    Join Date
    May 2009
    Posts
    827
    Thanks.
    I had actually already checked out that link before asking the question. I just asked it because it does not mention at that link whether it creates the file or not.

  4. #4
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    I just wish the C++ IO classes had something similar to the O_EXCL flag for open(). Otherwise it just opens the door to race conditions.
    "I am probably the laziest programmer on the planet, a fact with which anyone who has ever seen my code will agree." - esbo, 11/15/2008

    "the internet is a scary place to be thats why i dont use it much." - billet, 03/17/2010

  5. #5
    Registered User jeffcobb's Avatar
    Join Date
    Dec 2009
    Location
    Henderson, NV
    Posts
    875
    Quote Originally Posted by cpjust View Post
    I just wish the C++ IO classes had something similar to the O_EXCL flag for open(). Otherwise it just opens the door to race conditions.
    Wow you are right; even though most of my work is C++ nowadays I never used ofstream with any kind of access modifiers. If I needed to manage access to a file handle I just used the lower level calls. That said it would not be that hard to make your own wrapper for it and supply the access modifiers yourself..
    C/C++ Environment: GNU CC/Emacs
    Make system: CMake
    Debuggers: Valgrind/GDB

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. gcc link external library
    By spank in forum C Programming
    Replies: 6
    Last Post: 08-08-2007, 03:44 PM
  2. C++ std routines
    By siavoshkc in forum C++ Programming
    Replies: 33
    Last Post: 07-28-2006, 12:13 AM
  3. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  4. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM