Multiple file input with one function

Hi, can anyone give an example how to write a function that could work when you'd want to use multiple input files but not write separate functions? I couldn't find anything about this in the tutorials.

Hi, can anyone give an example how to write a function that could work when you'd want to use multiple input files but not write separate functions?

Could you please explain better what you’re trying to achieve?
You may of course open as many files as you wish inside one function:

myfile1.txt:
Beauty will save the world (Fyodor Dostoyevsky).

myfile1.txt:
The best time to plant a tree was twenty years ago. The second best time is now (Iranian proverb).

main.cpp:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <fstream>
#include <iostream>
#include <limits>
#include <string>

int openTwoFiles(std::string& filename1, std::string& filename2);

int main()
{
    std::string file1 = "myfile1.txt",
                file2 = "myfile2.txt";
    std::cout << "\nI've just opened (and closed) " 
              << openTwoFiles(file1, file2) << " files in one function.\n";

    std::cout << "\nPress ENTER to continue...\n";
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    return 0;
}


int openTwoFiles(std::string& filename1, std::string& filename2)
{
    int opened_file_counter = 0;
    std::ifstream file1(filename1);
    std::string sentence;
    std::getline(file1, sentence);
    std::cout << sentence << '\n';
    
    opened_file_counter++;

    std::ifstream file2(filename2);
    std::getline(file2, sentence);
    std::cout << sentence << '\n';

    opened_file_counter++;
    
    file1.close();
    file2.close();

    return opened_file_counter;
}


output:
Beauty will save the world (Fyodor Dostoyevsky).
The best time to plant a tree was twenty years ago. The second best time is now (Iranian proverb).

I've just opened (and closed) 2 files in one function.

Press ENTER to continue...

It's not clear from the OP if he means open two files in the same function as enoizat demonstrated, or if the OP meant to use the same function to process multiple files.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <fstream>
#include <iostream>
#include <limits>
#include <string>
using namespace std;

void process_file (string& filename);

int main()
{   string file1 = "myfile1.txt",
           file2 = "myfile2.txt";

    process_file (file1);
    process_file (file2);
    return 0;
}

void process_file (string & filename)
{   ifstream file (filename.c_str());
    
    string sentence;
    getline(file, sentence);
    cout << sentence << '\n';    
    file.close();    
}

Topic archived. No new replies allowed.