Hey, what I am trying to do is change the way people open text files in c++. What I want to do is:

open("example.txt");

which will then open the text file "example.txt"

and have a header file that displays like:

string line;
  ifstream file ("example.txt");
  if (file.is_open())
  {
    while (! file.eof() )
    {
      getline (file,line);
      cout << line << endl;
    }
    file.close();
  }

  else cout << "Unable to open file"; 

  return 0;
}

So that I do not have to type that every time I want to open a file, help please :( thank you, Phil

One, site rule, CodeTags!!
Two, use functions void FileHandler::open(const char *name, const int &mode); .
Three, don't bother with eof(). Try, while(getline(file, line)) .

If I understand your question correctly, you want a simpler method for reading files. I suppose you could write a simple function that returns all the lines of text as a vector of strings:

std::vector<std::string>* return_textfile(std::string filename)
{ 
  std::vector<std::string>* data;
  std::ifstream textfile(filename.c_str());
  std::string line;
  
  if (textfile)
  {
    data = new std::vector<std::string>; // don't forget to deallocate this once you're done with it!
    while ( getline(textfile, line) )
    {
      data->push_back(line);
    }
  }
  
  return data;
}

Other than that, though, you pretty much have to do it yourself. How else are you going to know when you reach the end of the file? (Which, by the way, should not be accomplished with the eof/feof function.)

Yeah but would like to open the files as:

open ("example.txt");

in a .cpp file

is this possible?

This goes in header:

class FileHandler
{
    private:
                vector<string> lines;
    public:
                void open(const char *name, const int &mode);
}

Your code goes in C++ file:

void FileHandler::open(const char *name, const int &mode)
{
    //place it into vector
}

And as I said, try to leave questions in the forums, not PMs.

fixed :) Works now, thank you everyone who has helped me! Much appreciated :)

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.