Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
467 views
in Technique[技术] by (71.8m points)

ifstream - 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!
";
    }
    else
    {
        cout << "File Did Not Open!
";
    }

    return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!
";
    }
    else
    {
        std::cout << "File Did Not Open!
";
    }

    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...