samedi 30 septembre 2017

How to create a map of std::ofstream objects

How can I create 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?

This is my header file:

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

#ifndef WRITE_FILES_H
#define WRITE_FILES_H

typedef std::map<int, std::ofstream> FileMap;

class writeFiles {
public:
    static void openFile (int num);
    static void writeTextFile (int num, string dataWrite, bool append);
    static void closeAllFiles ();
private:
    static std::string getName (int num);
    static FileMap fileMap;
};

#endif

Here is my cpp file:

#include "writeFiles.h"

FileMap writeFiles::fileMap = {};

void writeFiles::writeTextFile (int num, std::string dataWrite, bool append) {
    if (!fileMap.count(num)) {
        openFile(num);
    }
    if (!append) {
        fileMap[num].close();
        std::ofstream w;
        w.open(getName(num), std::fstream::out);
        w << dataWrite;
        fileMap[num].open(getName(num), std::fstream::out | std::fstream::app);
    } else {
        fileMap[num] << dataWrite;
    }
}

void writeFiles::openFile (int num) {
    fileMap.emplace(num, std::ofstream(getName(num)));
}

void writeFiles::closeAllFiles () {
    for (auto const &ent : fileMap) {
        ent.second.close();
    }
}

std::string writeFiles::getName (int num) {
    return "./temp/matrix/matrix" + std::to_string(num) + ".txt";
}

Aucun commentaire:

Enregistrer un commentaire