我有一个程序可以创建一个对象并使用该对象的一个函数,该函数接受两个文件名并从中读取数据并设置其值。
对象应该检查 ifstream
是自己打开还是应该在 main
函数中完成,首先尝试创建一对 ifstream
值并将它们传递给这个函数?有一个草图:
int main() {
Myclass *m = new Myclass();
string file1, file2;
…initialize file1, file2…
Myclass.readFromFiles(file1, file2);
delete m;
}
在我的课上:
void readFromFiles(const string &file1, const string &file2) {
std::ifstream infile1(file1);
if (!infile1.is_open()) { throw std::runtime_error("Could not open file"); }
infile1 >> value;
std::ifstream infile2(file2);
if (!infile2.is_open()) { throw std::runtime_error("Could not open file"); }
infile2 >> value2 >> value3;
}
或者说
std::ifstream open_file(std::string filename) {
std::ifstream infile(posesFilename);
if (!infile.is_open()) {
throw std::runtime_error("Could not open file");
}
else
return infile;
}
int main() {
Myclass *m = new Myclass();
string file1, file2;
…initialize file1, file2…
try{
std::ifstream f1 = open_file(file1);
std::ifstream f2 = open_file(file2);
Myclass.readFromFiles(f1, f2);
}catch (runtime_error e){
cout<< e.what() <<endl;
}
delete m;
}
在我的课上:
void readFromFiles(std::ifstream &f1, std::ifstream &f2)
f1 >> value;
f2 >> value2 >> value3;
}
最佳答案
在前一种情况下,您正在让函数调用者的生活更轻松。他们只需要将两个文件名传递给您的方法。该方法负责打开和关闭文件。如果您从多个位置调用此方法,您就减少了重复代码的数量。它也不是很灵活:如果调用者有 ifstream&
引用,但没有文件名,他们不能调用你的 readFromFiles(filename1, filename2)
方法。
在后一种情况下,调用者可以调用您的 readFromFiles()
,无论他们是否有 ifstream&
引用,或者如果他们只有文件名,则首先打开文件。此外,可以使该方法更加灵活。将预期参数更改为 istream&
而不是 ifstream&
将允许您使用任何输入流作为源来读取数据。例如,可以在构造 std:strstream
的地方创建一个单元测试,并将其传递给您的读取数据方法。
为了两全其美,提供两种方法:
void readFromFiles(const string &file1, const string &file2) {
std:ifstream f1(file1);
if (!f1.is_open()) { throw std::runtime_error("Could not open file"); }
std:ifstream f2(file2);
if (!f2.is_open()) { throw std::runtime_error("Could not open file"); }
readFromFiles(f1, f2);
}
void readFromFiles(std:istream& f1, std:istream& f2) {
// ...
}
您为调用者提供了便利和灵 active 。如果调用者需要知道这两个文件中的哪一个未能打开(例如,如果“file1”不存在,他们可能想回退到“file1_default”,如果“file2”不存在,则回退到“file2_default” ),他们可以完全控制打开文件和任何打开失败的报告。
关于c++ - 程序应何时通知用户它无法打开文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35997988/