c++ - 在函数中打开文件并在 main 中使用它

标签 c++

我有一个学校项目。该项目要求我编写一个名为 openFiles 的函数。所以我需要在函数内部打开一个文件并在 main 或其他函数中使用它。我怎样才能做到这一点?假设我的文件名为“1”

#include<iostream>
#include<string>
#include<fstream>
using namespace std;
void openFiles(string);
main() {
    openFiles("1");
    string str;
    while(file>>str)cout<<str;
}
void openFiles(string str){
    fstream file;
    file.open(str);
    
}

最佳答案

因为fstream有一个move constructor ,您可以将 fstream 对象作为 openFiles 的结果返回,如下所示:

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

fstream openFiles(string);

int main() {
    auto file = openFiles("1");
    string str;
    while(file>>str)cout<<str;
}

fstream openFiles(string str){
    fstream file;
    file.open(str);
    return file;
}

当然,你应该检查打开是否成功。

关于c++ - 在函数中打开文件并在 main 中使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65190240/

相关文章:

c++ - 'class Poco::XML::Element' 没有名为 'getNodeByPath' 的成员

c++ - 异步 ReadFile() 导致运行时错误?

C++:取消引用实际上在做什么?

c++ - 是否有一组 Objective-C 包装器来 boost 库?

c++ - Windows 上的堆损坏,但 Linux 上没有

c++ - std::wcout << L"élève"的意外输出;在 Windows 外壳中

c++ - 还是观察者模式?

c++ - 使用 CXX 社区插件在 Sonarqube-5.6.6(LTS) 中导入 Gcov 报告

c++ - 类型 'wxMenuBar'必须实现继承的纯虚方法 'wxMenuBarBase::GetLabelTop'

c++ - "candidate template ignored: substitution failure:"编译错误?