通过另一个函数打开一个 fstream

opening an fstream through another function

我正在创建一个程序,它在 main() 中声明一个 fstream,但在另一个函数 open_file() 中打开它,并通过另一个函数 print() 打印文件。但似乎文件在 open_file() 结束时自动关闭,因为 print() 没有显示输出。

这是我的代码。

#include <iostream>
#include <string>
#include <conio.h>
#include <fstream>
using namespace std;

void open_file(fstream &file)
{
    string name;
    cout << "Enter filename : ";
    cin >> name;
    file.open(name, ios::app);
    file.seekg(0);
}

void print(fstream &file)
{
    string temp;
    while(!file.eof())
    {
        getline(file, temp);
        cout << temp;
    }
}

int main()
{
    fstream file;
    open_file(file);
    print(file);
    return 0;
}

您以 append 模式打开文件,这是一种写入模式而不是读取模式。所以你打开文件只是为了写入而不是为了读取。

另外,不要使用while (!file.eof()),它不会像你期望的那样工作。而是 while (getline(...)).