有谁知道为什么文件打不开?我还尝试将“infile.txt”放入程序文件夹和调试文件夹中,但我用来检查打开错误的方式都触发了它无法打开的意思。我知道我可以对位置进行硬编码,但我不想这样做。
我听说你应该这样做 stringobj.c_str()
但我不知道这是否准确?
#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
ifstream infile;
ofstream outfile;
string fileloc = "infile.txt";
infile.open(fileloc);
if (!infile)
{
cout << "open fail 1" << endl;
}
bool fail = infile.fail();
if (fail)
{
cout << "open fail 2";
}
return 0;
}
原文由 Stackoverflow 发布,翻译遵循 CC BY-SA 4.0 许可协议
请注意,目录结构(至少对于 VS2013)是
默认情况下,该程序在项目目录中运行(即使它构建到解决方案/调试目录)。
如果您在启动项目时接受了默认命名约定,则应将文件放在“Projects\ConsoleApplication1\ConsoleApplication1”目录中,而不是“Projects\ConsoleApplication1”