【发布时间】:2015-11-16 18:45:04
【问题描述】:
#include<conio.h>
#include<iomanip>
#include<cmath>
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
fstream afile;
afile.open("example.txt");
afile<<"Hi I am Unnat";
afile.close();
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
cout << line << '\n';
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
我在这里得到的输出总是无法打开文件,当我检查文件夹时我没有找到 example.txt 请帮忙。
【问题讨论】:
-
试试
afile.open("example.txt", std::ios::out); -
您是否阅读过有关给您带来麻烦的功能的文档? en.cppreference.com/w/cpp/io/basic_fstream/open 调用en.cppreference.com/w/cpp/io/basic_filebuf/open?
-
您检查是否可以打开输入文件,但不能打开输出文件。这是为什么呢?
-
@RSahu
std::fstream::open的默认打开模式是ios_base::in|ios_base::out,所以out已经设置好了。 -
@JoachimPileborg:是的,但是
ios_base::inrequires an existing file。 RSahu 是正确的 — you needstd::ios::outand notstd::ios::in, to get automatic file creation.
标签: c++