程序中打开txt文件

程序中打开txt文件

本文介绍了无法使用Visual Studio 2019在C ++程序中打开txt文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用XCode一段时间后,我才刚开始使用Visual Studio 2019.我总是能够在XCode中打开txt文件,但是现在我无法在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 nowI can't open them in Visual Studio 2019.

基本上,我要做的是在调试"选项卡中按不调试就开始",并收到错误消息文件未打开!".从我写的else语句中得出.我不确定这是否与txt文件的位置或文件路径有关.

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.

下面是到目前为止我一直在使用的简单程序弄清楚如何在Visual Studio 2019中打开txt文件:

Below is the simple program that I've so far been usingto 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;
}

推荐答案

您正在使用相对文件路径打开文件.调用进程的当前工作目录"可能与您期望的不一样(请检查 GetCurrentDirectory() 进行验证).打开文件时,请始终使用绝对文件路径.

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.

例如,如果文件与EXE位于同一文件夹中,请使用 GetModuleFileName() 以获取EXE的完整路径,然后将文件名部分替换为所需的文件名:

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

这篇关于无法使用Visual Studio 2019在C ++程序中打开txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 00:19