【问题标题】:Specifying a path for a user defined file name [closed]为用户定义的文件名指定路径 [关闭]
【发布时间】:2019-09-02 18:18:02
【问题描述】:

我正在尝试弄清楚如何在用户命名/定义文件后指定文件的创建位置。

我正在使用的教科书对此没有任何帮助,我尝试弄乱 .open 语句中路径的定义方式,但我认为有些事情我不知道。当我定义一个路径时,因为它用引号括起来,我认为文件名变量被视为字符串文字,最终创建一个名为“文件名”的文件,而不是用户输入的任何内容。

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
    char response;
    string filename;
    ofstream fileCheck1;
    ifstream fileCheck;
    cout << "Create file? Y(yes) or N(no)\n";
    cin >> response;
    if (response == 'y' || response == 'Y')
    {
        cout << "Please enter file name: ";
        cin >> filename;

        fileCheck1.open (filename);
        if (fileCheck1)
            cout << "file created successfully\n";
        else
            cout << "error opening file\n";
    }
    else if (response == 'n' || response == 'N')
        cout << "press enter to exit\n";
    else
        cout << "invalid input\n";
    cin.get();
    cin.get();
    return 0;
}

默认情况下,文件会在 Visual Studio 的项目文件所在的位置创建。

【问题讨论】:

  • 阅读“当前工作目录”以及它可能始终是可执行文件的位置。

标签: c++ file input ofstream


【解决方案1】:

默认情况下,文件会在 Visual Studio 的项目文件所在的位置创建。因为在工作目录设置中指定了 $(ProjectDir)。考虑:

right-click on your project -> Properties -> configuration properties -> Debugging -> Working Directory

始终确保您通过窗口顶部的下拉列表更改/查看该窗口中的活动配置和活动平台设置。 这是使用 Visual Studio(F5) 启动程序时 Visual Studio 用作当前工作目录的路径。

如果您直接从 debug/release 文件夹运行 .exe,它将在 .exe 文件路径中创建该文件,这是您当前的工作目录。

您可以将上述设置更改为 $(OutputPath) 以使 Visual Studio 的行为相同,或者按 F5 运行程序或双击 .exe 文件

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-10
    • 1970-01-01
    • 1970-01-01
    • 2021-08-19
    • 1970-01-01
    • 2012-02-03
    • 2012-06-06
    相关资源
    最近更新 更多