VS C ++程序仅在从文件夹运行.exe时才有效? [不是VS调试]

时间:2009-08-30 21:44:57

标签: c++ visual-studio-2008 debugging exe

调试输出:

  

文件已打开...

     

文件内容:

.exe的输出(从/ project / debug双击运行):

  

文件已打开...

     

文件内容:        一号线        2号线        等。

源代码:

#include <iostream>
#include <fstream>
#include <regex>
#include <string>
#include <list>

using namespace std;
using namespace tr1;


int main()
{
    string line;
    list<string> dataList;

    ifstream myFile("test_data.txt");
    if (! myFile)
    {
        cout << "Error opening file. \n";
        return 0;
    }
    else
    {
        cout << "File opened... \n";
        while( getline(myFile, line) ) {
            dataList.push_back(line);
        }
    }

    cout << "\n\n File contents:";

    list<string>::iterator Iterator;
    for(Iterator = dataList.begin(); 
            Iterator != dataList.end();
            Iterator++)
    {
        cout << "\t" + *Iterator + "\n";
    }




    getchar();
    return 1;
}

谢谢你的帮助!

我现在明白了这个问题,谢谢。显然,这也表明这种文件错误处理方法毫无价值。我也纠正了这一点。再次感谢。

3 个答案:

答案 0 :(得分:4)

您对此行进行编码的方式:

ifstream myFile("test_data.txt");

表示代码正在当前工作目录中查找文件。

当您在调试器外部运行/project/debug(在您的情况下),这可能是文件的位置。

当您在调试器内运行时(可能)\project,它将不包含该文件。

您需要拥有该文件的两个副本,硬编码文件的完整路径,或者在运行时指定文件。

答案 1 :(得分:2)

您还可以在VC的项目的Debug属性页面中指定工作目录(它将在哪里查找test_data.txt)。

答案 2 :(得分:1)

从Visual Studio启动时,您的.exe通常从Debug/../运行。当您双击它时,它将在'Debug /'。

中运行

移动test_data.txt,或者像大多数开发人员那样移动,并创建一个输出目录,在该目录中运行二进制文件和数据。