简体   繁体   English

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

[英]VS C++ program only works when .exe is run from folder? [not VS debug]

Output from debug: 调试输出:

File opened... 档案已开启...

File contents: 文件内容:

Output from .exe (run via double click from /project/debug): .exe的输出(通过双击/ project / debug运行):

File opened... 档案已开启...

File contents: line1 line2 etc. . 文件内容:line1 line2等。 .

Source code: 源代码:

#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;
}

thank you for your help! 谢谢您的帮助!

i now understand the problem, thank you. 我现在明白了这个问题,谢谢。 obviously, this also shows that this method of error handling for files is worthless. 显然,这也表明这种错误处理文件的方法毫无价值。 I have corrected that as well. 我也纠正了。 Thanks again. 再次感谢。

The way you've coded this line: 您编写此行的方式:

ifstream myFile("test_data.txt");

means that the code is looking for the file in the current working directory. 表示代码正在当前工作目录中查找文件。

When you run outside the debugger that will be /project/debug (in your case), which is where the file presumably is. 当您在调试器之外运行时,调试器将是/project/debug (在您的情况下),这大概是文件所在的位置。

When you run inside the debugger that will (probably) be \\project , which won't contain the file. 当您在调试器中运行时(可能)是\\project ,其中将不包含文件。

You'll need to either have two copies of the file, hard code the full path to the file, or have some way of specifying the file at runtime. 您将需要具有文件的两个副本,对文件的完整路径进行硬编码,或者具有在运行时指定文件的某种方式。

您还可以在VC中为您的项目的“调试”属性页中指定工作目录(它将在其中查找test_data.txt)。

Your .exe is normally run from Debug/../ when started from Visual Studio. 从Visual Studio启动时,您的.exe通常是从Debug/../运行的。 When you double-click on it, it runs in 'Debug/'. 当您双击它时,它将在“ Debug /”中运行。

Either move your test_data.txt , or do as most developers and create an output directory where your binaries and data are exported before run. 要么移动您的test_data.txt ,要么像大多数开发人员一样做,并创建一个输出目录,您的二进制文件和数据在运行之前会被导出。

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

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