0

How should I add std::ofstream objects to a map of std::ofstream objects in c++?

I have tried solutions from other related questions, but I keep getting a segmentation fault. The problem is occurring in my openFile function.

I found another question relating to this, and tried using map::emplace, but I got a segmentation fault: 36817 Segmentation fault: 11
Is it possible to handle std::ofstream with std::map?

#include <fstream>
#include <iostream>
#include <map>

std::map<int, std::ofstream> writeFiles::fileMap = {};

void writeFiles::openFile (int num) {
    fileMap.emplace(num, std::ofstream(getName(num))); // This is where the problem is
}

std::string writeFiles::getName (int num) {
    return "./temp/matrix/matrix" + std::to_string(num) + ".txt";
}
PiGuy2
  • 3
  • 3
  • 3
    **Where** does the segfault happen? How does the other question not help you? What do you not know how to do? "Please fix this" is not a question – Passer By Sep 30 '17 at 14:24
  • The segmentation fault is in the openFile function, and the solution for the other question said to use the emplace function, which is resulting in the segmentation fault. – PiGuy2 Sep 30 '17 at 15:05
  • 1
    https://stackoverflow.com/help/mcve – Bill Lynch Sep 30 '17 at 15:09
  • you should be using a map of strings and not a map of ofstreams. load the string into the ofstream when you are ready to use it. – Matthew Sep 30 '17 at 20:12
  • 1
    I am running a program that writes thousands of lines of text one line at a time, and to multiple files. I am trying to make the code more efficient by only opening each file once, at the start of the code. – PiGuy2 Sep 30 '17 at 21:42
  • @Matthew I think that defeats the purpose of using the map – KansaiRobot Dec 23 '21 at 06:12

0 Answers0