Search code examples
c++fileinputofstream

Specifying a path for a user defined file name


I'm trying to figure out how to specify where a file is created after it is named/defined by the user.

The textbook I'm using doesn't give any help on this and I've tried messing around with how the path is defined in the .open statement, but I think there is just something that I'm unaware of. When I do define a path, because its enclosed in quotes, I think the filename variable gets taken as string literal which ends up creating a file named "filename" instead of whatever the user has input.

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

By default, the file gets created where ever the project files are for visual studio.


Solution

  • By default, the file gets created where ever the project files are for visual studio. because of $(ProjectDir) specified in Working Directory setting. consider:

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

    always make sure you are changing/viewing the active configuration and active platform setting in that window by dropdown lists on top of the window. this is the path Visual Studio uses as the current working directory when you start the program using Visual Studio(F5).

    if you run the .exe from directly from the debug/release folder it will create the file just in the .exe file path which is your current working directory.

    you can change the mentioned setting to $(OutputPath) to make identical behavior by Visual Studio either Run the Program by F5 or by double-clicking the .exe file