如何显示我在第一个函数中已经创建的文件的内容

How can I display the content of the file that I already created in the first function?

本文关键字:创建 函数 文件 第一个 何显示 显示      更新时间:2023-10-16
//it is  a function to take file name and create it.   
void createfile(string filename)
{
    ofstream file;
    file.open(filename,ios::out);
    if(file.fail())
    {
        cout<<"file is failed"<<endl;
    }
    else
    {
        cout<<"file is opened"<<endl;
    }
}
//it is a function which takes name of file and display it's content.  
void displaycontent(string name) 
{
    ifstream file;
    file.open(name);
    string y;
    while(!file.eof())
    {
        getline(file,y);
        cout<<y<<endl;
    }
}

如何显示我在第一个函数中已经创建的文件的内容?

int main()
{
    string filename;
    cin>>filename;
    createfile(filename); 
    displaycontent(filename);
    return 0;
}

该程序永远不会将任何内容写入文件,因此没有内容可以显示。另外,循环是错误的。如果发生错误读取文件,则file.eof((永远不会是正确的,以下将永远循环。

void displaycontent(string name) 
{
    ifstream file;
    file.open(name);
    string y;
    while(!file.eof()) // WRONG
    {
        getline(file,y);
        cout<<y<<endl;
    }
}

相反,您想要此(省略错误处理(:

void display_file(const string &file_name) // Note pass by reference
{
    std::ifstream file;
    file.open(file_name);
    std::string y;
    while(std::getline(file,y)) {
       std::cout << y << 'n';
    }
}

或更好,

void display_file(const string &file_name) 
{
    std::ifstream file(file_name);
    std::cout << file.rdbuf();
}

在显示功能(在其他范围内(中调用创建功能...随着创建函数按值传递,因此内部内部发生的任何更改都将留在范围内