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

天大地大妈咪最大 提交于 2021-02-02 03:46:35

问题


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

回答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;
}


来源:https://stackoverflow.com/questions/57281750/cant-open-txt-files-in-c-program-with-visual-studio-2019

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!