lundi 31 janvier 2022

vector variable scope in C++ [duplicate]

I am writing a program in C++ that is reading some files with fstream then writes with a simple function and after that closes them.

I created a struct and I keep here filetag, filepointer and lines. The problem is that from main I can't write or close the file ... but I can access filetag and lines variables. Here is my code:

struct Fileoutput
{
    string filetag;
    std::fstream* filepointer;
    int lines = 0;
};

static std::vector<Fileoutput> vect_fileoutputs;

static void open_files()
{
    // open all
    struct Fileoutput fo_all;
    fo_all.filetag = "all";
    fo_all.lines = 0;
    std::fstream fs_all;
    fs_all.open("all.log",std::fstream::out | std::fstream::app);
    fo_all.filepointer = &fs_all;
    //*fo_all.filepointer << "something from struct" << endl; // here it is working, in other scope ... no
    vect_fileoutputs.push_back(fo_all);
    /*
    for(const struct Fileoutput fo : vect_fileoutputs)
    {
        *fo.filepointer << "something from vect" << endl; // here is working
    }
    */

    // open error
    struct Fileoutput fo_error;
    fo_error.filetag = "error";
    fo_error.lines = 0;
    std::fstream fs_error;
    fs_error.open("error.log",std::fstream::out | std::fstream::app);
    fo_error.filepointer = &fs_error;
    vect_fileoutputs.push_back(fo_error);
}

static bool write_to_outputfile(char* outputfile,char* content)
{
bool write = false;
for(const struct Fileoutput fo : vect_fileoutputs)
{
    if(strcmp(fo.filetag.c_str(),outputfile) == 0)
    {
        printf("Writing [%s] to [%s]\n",content,outputfile);
        std::fstream* fs_write;
        fs_write = fo.filepointer;
        *fo.filepointer << content; // NOT WORKING ... seg fault
        write = true;
        break;
    }
}

return write;
}

static void close_files()
{
    for(const struct Fileoutput file_output: vect_fileoutputs)
    {
        printf("Closing file [%s]\n",file_output.filetag.c_str());
        std::fstream* fs_temp;
        fs_temp = file_output.filepointer;
        fs_temp->close(); // NOT WORKING ... seg fault
        printf("Closed [%s]\n",file_output.filetag.c_str());
    }
}

int main(int argc, char* argv[])
{
    open_files();

    write_to_outputfile((char*)"all",(char*)"something1\n");
    write_to_outputfile((char*)"all",(char*)"something2\n");
    write_to_outputfile((char*)"all",(char*)"something3\n");

    write_to_outputfile((char*)"error",(char*)"error\n");
    close_files();

    return 1;
}

The gdb error looks like :

gdb error :

Program received signal SIGSEGV, Segmentation fault.
0x0000000000405de9 in ?? ()
(gdb) x 0x0000000000405de9
0x405de9:   0xe8420348
(gdb) x 0x405de9
0x405de9:   0xe8420348
(gdb) x 0xe8420348
0xe8420348: Cannot access memory at address 0xe8420348
(gdb)

What is wrong with the code?

Aucun commentaire:

Enregistrer un commentaire