views:

228

answers:

6

Must be a simple answer but I am at a loss, here is the code that is returning an error. I have tried with and without the starting slash.

I won't know the full path, I want it to be relative from the exe, and that is the relative path. I tried escaping the slashes.

My problem is that i get "error opening file" when the file is there. why is it failing?

  ifstream myFile("/LOGS/ex090716.txt");
  if (myFile.fail()) {cout << "Error opening file";}
  else
  {
   cout << "File opened... \n";
   //string line;
   //while( getline(myFile, line) ) {
   // cmatch results;
   // regex rx("(p|q)(=)([^ %]*)");
   // regex_search(line.c_str(), results, rx);
   // string referringWords = results[3];
   //}
   myFile.close();
  }

thank you

+1  A: 

What is your problem exactly?! if you want to test if the file is open or not use is_open().

AraK
A: 

Do those slashes need to be escaped?

Charlie Salts
forward slashes don't need to be escaped
Evan Teran
Ah, right you are.
Charlie Salts
A: 

fail()

Check if either failbit or badbit is set.

The function returns true if either the failbit or the badbit is set. At least one of these flags is set when some error other than reaching the End-Of-File occurs during an input operation.

ifstream myFile("/LOGS/ex090716.txt");
  if (!myFile.fail()){cout << "Error opening file";}  
  else  {   
    cout << "File opened... \n";
   }
myFile.close();

OR

ifstream myFile("/LOGS/ex090716.txt");
  if (!myFile){cout << "Error opening file";}  
  else  {   
    cout << "File opened... \n";
   }
myFile.close();
adatapost
A: 

Get rid of the leading slash

ifstream myFile("LOGS/ex090716.txt");
//...
GRB
A: 

Relative path: don't start with /

Relative to program dir rather than cd: you can't just use argv[0] if the program is found via PATH. I'm not sure what you can do that's portable. You may want to resolve symbolic links repeatedly.

On linux, readlink() on the file /proc/self/exe works.

On Windows, this is supposed to work:

TCHAR path[2048] = {0};
GetModuleFileName( NULL, path, 2048 );
const string exe_path( path );
const string exe_dir( exe_path.substr(0, exe_path.rfind("\\") + 1 );

In general, you should use http://www.boost.org/doc/libs/1%5F40%5F0/libs/filesystem/doc/index.htm

wrang-wrang
A: 

perror() can relative easy give you a detailed description of the problem

int fd = open("/LOGS/ex090716.txt", O_RDONLY);
if(fd == -1) {
    perror("cannot open file");
    exit(1); 
}

however this is not c++'ish.

neoneye