1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Creating Files from a Program

Discussion in 'C++' started by celticafro, Feb 2, 2009.

  1. celticafro

    celticafro New Member

    Feb 2, 2009
    Likes Received:
    Trophy Points:
    Hey folks. I had a question about file creation using the functionality supported by the #include <fstream> directive.

    Can the fstream type create new files during runtime? If so, how might I go about using it? Does that question make sense?

    I understand that a "text" file can be created by use of the ofstream type. ie, this line of code:

    ofstream file_out(filename);
    will attempt to open file filename in the root directory of the program, and if none is found, a file will be generated where it needs to be. My use of the ofstream type has been very reliable so far, and I have had few issues with it.

    However, creating files using the fstream type in binary mode has been more problematic for me. I thought that, with the proper mode flags, the fstream type would be more flexible than using just ofstream or ifstream. For example, this is how my C++ book might declares its fstream object, and then test for existence of a file filename:

    fstream binfil(filename, ios::binary | ios::in | ios::out);
    if (!fbin) {
    cout << "could not open file " << filename;
    return -1
    I can read and write to and from existing files using the binfil.read() and binfil.write() member functions, but actually creating the file still eludes me.

    So the question again -- can the fstream type be used to create new files, and if so, how?

    Thanks in advance for your insight,

Share This Page