简体   繁体   English

打开文件C ++时出现问题

[英]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. 我不知道完整路径,我希望它与exe是相对的,这就是相对路径。 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 谢谢

What is your problem exactly?! 你到底是什么问题? if you want to test if the file is open or not use is_open() . 如果要测试文件是否打开,请使用is_open()

fail() 失败()

Check if either failbit or badbit is set. 检查是否设置了故障位或故障位。

The function returns true if either the failbit or the badbit is set. 如果设置了故障位或故障位,则该函数返回true。 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();

Get rid of the leading slash 摆脱领先的斜线

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

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. 相对于程序目录而不是cd:如果通过PATH找到程序,则不能仅使用argv [0]。 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. 在Linux上,文件/ proc / self / exe上的readlink()有效。

On Windows, this is supposed to work: 在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 );

In general, you should use http://www.boost.org/doc/libs/1_40_0/libs/filesystem/doc/index.htm 通常,您应该使用http://www.boost.org/doc/libs/1_40_0/libs/filesystem/doc/index.htm

perror() can relative easy give you a detailed description of the problem perror()可以相对容易地为您提供问题的详细说明

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

however this is not c++'ish. 但是,这不是C ++的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM