Thread: Variable file names in file i/o

  1. #1
    Registered User
    Join Date
    Jan 2009
    Posts
    2

    Variable file names in file i/o

    Hello. I'm trying to write a program that includes saving text to a file. I wish to have the filename entered by the user. I know how to write to a file, but I'm not sure how to allow the user to define that file. This is the function I tried creating, and when added, my program will not compile:
    Code:
    void filewrite() {
    string filen = "";
    cout<<"Enter filename(will be overwitten if exists):";
    cin>>filen;
     ofstream myfile;
      myfile.open (filen, ios::trunc);
      myfile << "Writing this to a file.\n";
      myfile.close();
    }
    I appreciate any assistance you can render me.

    Edit:
    Here are my includes:
    Code:
    #include <iostream>
    #include <sstream>
    #include <fstream>
    Here is the error:

    cpp:15: error: no matching function for call to ‘std::basic_ofstream<char, std::char_traits<char> >:pen(std::string&, const std::_Ios_Openmode&)’
    /usr/include/c++/4.3/fstream:626: note: candidates are: void std::basic_ofstream<_CharT, _Traits>:pen(const char*, std::_Ios_Openmode) [with _CharT = char, _Traits = std::char_traits<char>]
    Last edited by jesseee; 01-14-2009 at 11:52 PM. Reason: Adding more info

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > myfile.open (filen, ios::trunc);
    Use
    myfile.open (filen.c_str(), ios::trunc);

    The clue in the error message is here
    candidates are: void std::basic_ofstream<_CharT, _Traits>::open(const char*, std::_Ios_Openmode) [with _CharT = char, _Traits = std::char_traits<char>]

    The c_str() method of a string returns something of the appropriate type.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Jan 2009
    Posts
    2
    Thank you very much. I suspect this method will come in very handy in the future.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Formatting the contents of a text file
    By dagorsul in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2008, 12:36 PM
  2. C++ std routines
    By siavoshkc in forum C++ Programming
    Replies: 33
    Last Post: 07-28-2006, 12:13 AM
  3. File I/O problem
    By 81N4RY_DR460N in forum C++ Programming
    Replies: 12
    Last Post: 09-03-2005, 12:14 PM
  4. User entering I/O File names at command line
    By Wiggin in forum C++ Programming
    Replies: 6
    Last Post: 04-27-2002, 12:43 AM