Can't open txt files in c++ program with Visual Studio 2019

I just started using Visual Studio 2019 after using XCode for a while. I was always able to open txt files in XCode but now I can't open them in Visual Studio 2019.

Basically what I do is I press "Start Without Debugging" in the "Debug" tab I and get the error message "File Did Not Open!" from the else statement that I wrote. I am not sure if it has something to do with where the txt file is located or with the file path.

Below is the simple program that I've so far been using to figure out how to open txt files in Visual Studio 2019:

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

int main()
{
    ifstream fobj;
    fobj.open("input.txt");

    if (fobj)
    {
        cout << "File Opened!\n";
    }
    else
    {
        cout << "File Did Not Open!\n";
    }

    return 0;
}

Solution 1:

You are using a relative file path to open the file. The calling process' "current working directory" is likely not what you are expecting (check with GetCurrentDirectory() to verify). Always use absolute file paths when opening files.

For instance, if the file is in the same folder as your EXE, use GetModuleFileName() to get the EXE's full path, then replace the filename portion with your desired filename:

#include <iostream>
#include <fstream>
#include <string>

#include <windows.h>
#include <shlwapi.h>

int main()
{
    char filename[MAX_PATH] = {};
    ::GetModuleFileNameA(NULL, filename, MAX_PATH);
    ::PathRemoveFileSpecA(filename);
    ::PathCombineA(filename, filename, "input.txt");

    std::ifstream fobj;
    fobj.open(filename);

    if (fobj)
    {
        std::cout << "File Opened!\n";
    }
    else
    {
        std::cout << "File Did Not Open!\n";
    }

    return 0;
}