Hello All,

I would like the user to be able to choose the file_name (assuming it already exists) and be able to append information to it. However, this condensed version, below, of what I'm trying to do gives me a compilation error. I feel like it has something to do with the data type I chose for file_name. If I switch to char*, then the program compiles fine, but results in a bus error after executing it. I am a little new to this, any explanation would be greatly appreciated!

#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>

using namespace std;

int main()
{
    string file_name;
    ofstream infile;

    cout << "Enter name of file: ";
    cin >> file_name;

    infile.open( file_name, ios::app );

    cout << infile.fail();

    return 0;
}

Streams use bit flags to hold certain information. To manipulate these flags, you need to use the bitwise operators and special constants. You need to use the BITWISE OR to combine multiple file access modes when opening a file stream. One mode constant does not imply any other, they are completely independent.

infile.open( file_name, [B]ios_base::out |[/B] ios_base::app );

Also, if you want to use an std::string for the file name, you need to use the std::string::c_str() method to pull a C-style string out of it. This is why it sort-of worked when you tried to use a char*...

infile.open( file_name.c_str(), ios_base::out | ios_base::app );

You need to OR multiple file access modes together when opening a file stream. One mode constant does not imply any other, they are completely independent.

infile.open( file_name, [B]ios_base::out |[/B] ios_base::app );

Also, if you want to use an std::string for the file name, you need to use the std::string::c_str() method to pull a C-style string out of it. This is why it sort-of worked when you tried to use a char*...

infile.open( file_name.c_str(), ios_base::out | ios_base::app );

Wow! Thank you so much for your speedy effort.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.