我已经用C++编写了一个代码,该代码从文本文件中读取或使用ifstream
/ofstream
创建新的代码。我想添加一个支票.is_open
成员函数fstream
查看文件是否成功打开。它在主循环内正常工作。然后我试图创建外循环功能用于此目的,并调用它里面main
,和我有以下错误:C++无法检查函数中的ifstream/ofstream.is_open()
std::ios_base::ios_base(const std::ios_base&)
is private.
是否有可能使主环路以外的检查?怎么样?我究竟做错了什么?
如果您能提供帮助,我将不胜感激。你可以找到下面的代码。
P.S.我是C++中的新手,所以如果你看到任何问题,请不要过分批评不专业的编程方法。尽管任何改进建议都值得欢迎。
#include <iostream>
#include <fstream>
using namespace std;
void check_opened(ifstream toget, ofstream togive){
if(toget.is_open()){
cout<<"able to open file(toread.txt)"<<endl;
}
else {
cout<<"failure"<<endl;
}
if(togive.is_open()){
cout<<"able to create/open a file(newone.txt)"<<endl;
}
else {
cout<<"failure"<<endl;
}
}
int main() {
ifstream toget;
ofstream togive;
toget.open("toread.txt");
togive.open("newone.txt");
check_opened(toget,togive);
toget.close();
togive.close();
return 0;
}
无论您是否有'is_open'调用,都会发生错误。制作[mcve]的一部分正在挑战你的假设。 – chris
您正在将'toget'和'togive'值传递给'check_opened'函数。它看起来不允许复制'ifstream'和'ofstream's。尝试将它们作为引用或指针传递。 – gurka
@古尔卡,非常感谢,我用它作为参考,它的工作。 – UserRR