1 Replies - 178 Views - Last Post: 05 September 2012 - 06:08 PM Rate Topic: -----

#1 bennigan88  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 40
  • Joined: 07-April 12

Using a string's .open() inside a function

Posted 05 September 2012 - 06:03 PM

I am trying to make a function that takes in a file name in the form of a c-string, as well as a file stream, and open that file and link it to the stream, but I am getting an error: "42|error: 'struct std::basic_istream<char, std::char_traits<char> >' has no member named 'open'

What am I missing and how should I implement this idea? I don't want my int main cluttered up with file stream stuff. Here's my attempt:
#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;
const int MAX_STRING_SIZE=30;

void readfile(char filename[], istream& streamname);
/* takes in a file name represented by a c-string and
assigns it to an input file stream. requires header
file <fsream>*/

void getstring(char givenname[MAX_STRING_SIZE]);
/* takes c-string given by user and stores it in the
passed character array*/

void printfile(istream& streamname);
/* uses cout to print contents of the file passed
to the function*/

int main()
{
    ifstream fin;
    char filename[MAX_STRING_SIZE];

    readfile(filename, fin);



    return 0;
}

void readfile(char filename[], istream& streamname)
{
    streamname.open(filename);
    if (streamname.fail())
        cout << "Failed to open file." << endl;
    else
        cout << "File opened succesfully." << endl;
    return;
}

void printfile(istream& streamname)
{
    return;
}

void getstring(char givenname[MAX_STRING_SIZE])
{
    cin.getline(givenname,MAX_STRING_SIZE,'\n');
}




Is This A Good Question/Topic? 0
  • +

Replies To: Using a string's .open() inside a function

#2 Skydiver  Icon User is online

  • Code herder
  • member icon

Reputation: 1928
  • View blog
  • Posts: 5,737
  • Joined: 05-May 12

Re: Using a string's .open() inside a function

Posted 05 September 2012 - 06:08 PM

Yes. istream doesn't have open(), but ifstream does.
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1