Write vector values into multiple files at once

Hello,
I have the data in my vector. I am trying to write each vector value, say vector_name[0] into "examplezero.h" , vector_name[1] into "exampleone.h" and so on. The below code shows how I have created the files.

1
2
3
4
5
6
7
8
9
  	int co = 80;

	string name ="example";
	std::ofstream output_file[80];
	for (int i = 0; i < co; i++)
	{
	     output_file[i].open(name + std::to_string(i) + ".h");
	     output_file[i].close();
	}

I am trying to iterate over my vector and trying to write to my files. Here
1
2
3
4
5
6
7
8
9
        std::vector<string> rowname;  //This has all the values
        for (auto i = rowname.begin(); i != rowname.end(); ++i) 
	{
			
		std::ostream_iterator<std::string> \
                           output_iterator(output_file[80], "\n");
		std::copy(rowname.begin(), rowname.end(), output_iterator);
			
	}

When I am trying to write to the files it is crashing. Can you let me know what's wrong? I know the basics of C++ trying to learn the advanced concepts.
Thanks
Most modern OSes can handle a lot of file handles, but 80 in a single process might be pushing it.

Your main problem is that you are immediately closing the file after opening it (lines 7–8).
You might be better off just opening the file for every element of the vector:

1
2
3
4
5
6
7
vector<string> strings; // rowname?
int n = 0;
for (const auto& s : strings)
{
  std::ofstream f( "example" + to_string(n++) + ".h" );
  f << s << "\n";
}

Notice also that since your vector is just a list of std::string, you do not need to waste effort using an ostream_iterator<>. Just write the string.

Hope this helps.
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
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

int main()
{
    int co = 80;
    
    std::string name ="example";
    std::ofstream output_file[co];
    
    for (int i = 0; i < co; i++)
    {
        output_file[i].open(name + std::to_string(i) + ".h");
    }
    
    
    std::vector<std::string> rowname;
    std::string temp;
    for (int i = 0; i < co; i++)
    {
        temp = std::to_string(100*i);
        
        rowname.push_back(temp);
        output_file[i] << temp << '\n';
    }
    
    for(auto it:rowname)
        std::cout << it << '\n';
    
    
    for (int i = 0; i < co; i++)
    {
        output_file[i].close();
    }
    
    return 0;
}


PS Now I have to go and delete 80 files each having only one lousy number. Lucky they are not randomly named and/or located in random directories ... a definite force for evil if that occurred.
Last edited on
Topic archived. No new replies allowed.