2

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

4

5 回答 5

1

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

于 2009-09-04T03:32:16.550 回答
1

摆脱前导斜线

ifstream myFile("LOGS/ex090716.txt");
//...
于 2009-09-04T04:17:27.337 回答
0

perror() 可以相对容易地给你问题的详细描述

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

然而,这不是 c++'ish。

于 2009-09-04T06:19:02.547 回答
0

失败()

检查是否设置了故障位或坏位。

如果设置了故障位或坏位,则该函数返回 true。当在输入操作期间发生某些错误而不是到达文件结尾时,至少设置这些标志之一。

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

或者

ifstream myFile("/LOGS/ex090716.txt");
  if (!myFile){cout << "Error opening file";}  
  else  {   
    cout << "File opened... \n";
   }
myFile.close();
于 2009-09-04T03:38:07.463 回答
0

相对路径:不要以/

相对于程序目录而不是 cd:如果通过 PATH 找到程序,则不能只使用 argv[0]。我不确定你能做什么便携。您可能希望反复解析符号链接。

在 linux 上,文件 /proc/self/exe 上的 readlink() 有效。

在 Windows 上,这应该可以工作:

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

一般来说,您应该使用http://www.boost.org/doc/libs/1_40_0/libs/filesystem/doc/index.htm

于 2009-09-04T04:17:29.833 回答