0

嗨,我正在尝试将文本写入文件: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;
}

当我运行这个 XCode 时告诉我一个 exec 坏访问来自于data_file->open(datafilename.str().c_str(), ios::app);?我哪里错了?

4

2 回答 2

6
ofstream* data_file;
ofstream* incl_file;

您已将它们声明为指针,并且您正在使用它们而不为它们分配内存。这就是运行时错误的原因。

我建议您制作自动对象,如:

ofstream data_file;
ofstream incl_file;

然后将它们作为引用类型传递:

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
}
于 2011-10-10T07:48:00.913 回答
2

有指向流的指针是多么奇怪。问题是您从未初始化过此类指针,但仍尝试访问它们。您缺少几个news。

于 2011-10-10T07:48:23.620 回答