Nona Urbiz
Nona Urbiz

Reputation: 5013

problem opening file c++

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

Upvotes: 2

Views: 8089

Answers (5)

neoneye
neoneye

Reputation: 52201

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.

Upvotes: 0

Jonathan Graehl
Jonathan Graehl

Reputation: 9301

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_40_0/libs/filesystem/doc/index.htm

Upvotes: 0

GRB
GRB

Reputation: 4022

Get rid of the leading slash

ifstream myFile("LOGS/ex090716.txt");
//...

Upvotes: 1

KV Prajapati
KV Prajapati

Reputation: 94645

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();

Upvotes: 0

Khaled Alshaya
Khaled Alshaya

Reputation: 96869

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

Upvotes: 1

Related Questions