如何将.txt文件作为不同 cpp 中函数的参数传递

How to pass a .txt file as an argument for a function in a different cpp

本文关键字:cpp 函数 参数传递 txt 文件      更新时间:2023-10-16
int main()
{
    fstream file;
    file.open("new_file.txt" , ios::app);
    if (!file.is_open()){
        cout << "File does not exist yet !n";
        return 1;
    }
    string input;
    cout << "Add new line or edit? Write NEW or EDIT";
    cin >> input;
    if (input == "NEW")
    {
        add_new_info();
    }
    //.....
}

在另一个 cpp 中,我有:

int add_new_info()
{
    string aux;
    int count;
    cout << "Add line ID n";
    cin >> aux;
    file << aux << "; ";
    //...
}

所以基本上我想在main中打开txt文件,然后将其传递给add_new_info()。如何将txt file作为参数传递给另一个.cpp中的函数?

您可以只传递对打开文件的引用

int add_new_info(fstream& file)
{
    // add info to the file
}

并在main的电话

add_new_info(file);

就像 zett42 在评论中提到的那样,如果该函数不使用特定于文件流的任何内容,则使用参数 std::ostream& 也将允许将该函数用于其他类型的流,例如add_new_info(cout);在控制台上显示信息。