【问题标题】:problem opening file c++c++ 打开文件的问题
【发布时间】:2009-09-04 03:28:56
【问题描述】:

必须是一个简单的答案,但我不知所措,这是返回错误的代码。我试过带和不带斜线。

我不知道完整路径,我希望它是相对于 exe 的,这就是相对路径。我尝试转义斜线。

我的问题是当文件存在时我得到“错误打开文件”。为什么会失败?

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

谢谢

【问题讨论】:

  • 您要打开的文件的完整路径是什么?

标签: c++ file ifstream


【解决方案1】:

你的问题到底是什么?!如果要测试文件是否打开,请使用is_open()

【讨论】:

    【解决方案2】:

    去掉前面的斜线

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

    【讨论】:

      【解决方案3】:

      fail()

      检查是否设置了failbit或badbit。

      如果设置了failbit 或badbit,则该函数返回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();
      

      【讨论】:

        【解决方案4】:

        相对路径:不要以/开头

        相对于程序目录而不是 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

        【讨论】:

          【解决方案5】:

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

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

          然而这不是 c++'ish。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2020-01-22
            • 2011-10-03
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-03-27
            相关资源
            最近更新 更多