0

Hi I'm trying to write text to files with: ofstream

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <cstring>
#include <stdlib.h>

using namespace std;    


void init_log(ofstream* data_file, ofstream* incl_file, string algo){
    stringstream datafilename;
    datafilename << "report/data/" << algo << ".txt";
    stringstream includefilename;
    includefilename << "report/include/" << algo << ".tex";

    data_file->open(datafilename.str().c_str(), ios::app);
    incl_file->open(includefilename.str().c_str(), ios::app);
}

void write_log(ofstream* data_file, ofstream* incl_file, int size, double timesec){
    stringstream tow_data;
    tow_data << size << " " << timesec <<  endl;
    stringstream tow_incl;
    tow_incl << size << " & " << timesec << " \\\\ \\hline" << endl;

    *data_file << tow_data.str().c_str();
    *incl_file << tow_incl.str().c_str();
}

void close_log(ofstream* data_file, ofstream* incl_file){
    data_file->close();
    incl_file->close();
}
int main (int argc, const char * argv[]){

    double elapsed = 1.0;
    int test = 10;

    ofstream* data_file;
    ofstream* incl_file;

    init_log(data_file, incl_file, "hello");


    write_log(data_file, incl_file, text, elapsed);


    close_log(data_file, incl_file);

    return 0;
}

When I run this XCode tells me that an exec bad acces comes from data_file->open(datafilename.str().c_str(), ios::app); ? Where do I get wrong ?

Kami
  • 5,959
  • 8
  • 38
  • 51
  • 2
    No offense, but you need [a good C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – sbi Oct 10 '11 at 07:53
  • This is absolutely not an offence, but very appreciated ! – Kami Oct 10 '11 at 09:45

2 Answers2

6
ofstream* data_file;
ofstream* incl_file;

You've declared these as pointers, and you're using them without allocating memory for them. That is the reason of the runtime error.

I would suggest you to make then automatic objects, as:

ofstream data_file;
ofstream incl_file;

and then pass them as reference type:

void init_log(ofstream & data_file, ofstream* incl_file, string algo){
                     //^^^ reference
}

void write_log(ofstream & data_file, ofstream* incl_file, int size, double timesec){
                     //^^^ reference
}

void close_log(ofstream & data_file, ofstream* incl_file){
                     //^^^ reference
}
Nawaz
  • 353,942
  • 115
  • 666
  • 851
2

How odd having pointers to streams. The problem is that you never initialized such pointers but still try to access them. You are missing a couple of news.

K-ballo
  • 80,396
  • 20
  • 159
  • 169