bob
bob

Reputation: 49

How to convert a string to a ifstream

i am trying to open a file with ifstream and i want to use a string as the path (my program makes a string path). it will compile but it stays blank.

string path = NameOfTheFile; // it would be something close to "c:\file\textfile.txt"
string line;

ifstream myfile (path); // will compile but wont do anything.
// ifstream myfile ("c:\\file\\textfile.txt"); // This works but i can't change it
if (myfile.is_open())
{
   while (! myfile.eof() )
   {
      getline (myfile,line);
      cout << line << endl;
   }
}

I am using windows 7, My compiler is VC++ 2010.

Upvotes: 4

Views: 12784

Answers (4)

Amit Vujic
Amit Vujic

Reputation: 1788

//Check out piece of code working for me 
//---------------------------------------
char lBuffer[100];
//---
std::string myfile = "/var/log/mylog.log";
std::ifstream log_file (myfile.str());
//---
log_file.getline(lBuffer,80);
//---

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490028

Have you tried ifstream myfile(path.c_str());?

See a previous post about the problems with while (!whatever.eof()).

Upvotes: 5

Jim Brissom
Jim Brissom

Reputation: 32919

I'm unsure as to how this actually compiles, but I assume you are looking for:

#include <fstream>
#include <string>
//...
//...
std::string filename("somefile.txt");
std::ifstream somefile(filename.c_str());
if (somefile.is_open())
{
    // do something
}

Upvotes: 1

Fred Nurk
Fred Nurk

Reputation: 14212

string path = compute_file_path();
ifstream myfile (path.c_str());
if (!myfile) {
  // open failed, handle that
}
else for (string line; getline(myfile, line);) {
  use(line);
}

Upvotes: 7

Related Questions