无法使用ifstream打开文本文件

时间:2018-02-06 02:37:50

标签: c++

ifstream fin;
fin.open("‪C:\\Users\\Zach\\Desktop\\input.txt");
if (!fin) 
{
    cout << "e";
}

是打印我是使用完整路径还是仅使用资源文件中的input.txt

2 个答案:

答案 0 :(得分:0)

如果文件存在,请确保您已正确指定路径。由于您在Windows上运行,因此可以使用以下代码验证可执行文件的完整路径。

#include <iostream>
#include <fstream>
#include <string>
#include <windows.h>

#define BUFSIZE 4096

std::string getExePath()
{
    char result[BUFSIZE];
    return std::string(result, GetModuleFileName(NULL, result, BUFSIZE));
}

int main()
{
    std::ifstream infile("input.txt");
    if (infile.is_open())
    {
        std::cout << "Success!" << std::endl;
        infile.close();
    }
    else
    {
        std::cout << "Failed to open input.txt!" << std::endl;
        std::cout << "Executable path is ->" << getExePath() << "<-" << std::endl;
    }
    return 0;
}

这将允许您验证输入文件的路径是否正确,假设它与您的可执行文件并置。

答案 1 :(得分:-1)

您需要使用ifstream将输出定向到fin << "string";对象,而不是通过cout指向标准输出。

相关问题