运行 到 Visual Studio 时无法打开文件

Failing to open a file when running through Visual Studio

我有这个功能

void foo()
  {
   std::string path = "Test.txt" ;
  std::ifstream file;
  file.open(path);
  if (file.good()) // if the file opened up 
  {
        std::cout << "YAY" << std::endl;
  }
  else
  {
      std::cout << "ERROR!" << std::endl;
      getError();
  }
}

我的 .exe 文件所在的文件夹中有一个文件 "Test.txt"。 运行程序直接通过cmd打开文件成功,但是运行程序通过Visual studio打开文件失败。 我尝试用完整路径打开文件,但结果还是一样。

I have a file "Test.txt" in the folder where I have the .exe file

这无关紧要。该进程甚至不知道.exe文件在哪里!

重要的是进程的当前工作目录,它可能不是加载 .exe 的地方。

在 Visual Studio 中调试时,我认为这是您项目的根文件夹。

系统在其他目录(不是包含 exe 文件的目录)中运行可执行文件。您可以通过创建文件来发现是哪一个:

void foo()
{
    std::ofstream hey("whatever");
}

然后查看创建文件的位置。这是系统运行你的exe文件的目录。

默认情况下,Visual Studio 的工作目录是项目的文件夹(您通常可以在其中看到代码文件和项目文件),因此请确保您的文件在那里。 EXE 位于 Debug 文件夹中,这是无关紧要的,因为它不是 Visual Studio 的工作目录。

您可以这样更改工作目录:

https://msdn.microsoft.com/en-us/library/ms171340%28v=vs.90%29.aspx

干杯。