У меня есть класс с методом run()
, который должен писать "заголовочный" файл, выполнять некоторые вычисления и записывать результаты вычислений в отдельный файл. Моя проблема в том, что файлы никогда не записываются. Отладчик кода VS, кажется, указывает, что вызовы .close()
в методах записи никогда не достигаются. Однако даже когда я пытаюсь перемежать .flush()
методы, в файл не записывается никакого содержимого.
Методы записи вызывают встроенную переменную, объявленную в Experiments.h
, которая равна #include
d в file.`Experiments :: OUTPUT_DIR = "../results/".
Я так понимаю, проблема в том, что контент никогда не записывается, потому что .close()
никогда не вызывается в скомпилированном коде. Но как это исправить?
// main method in the compiled file
int main(){
Experiments::Experiment* experiment = new Experiments::UniformRandomAgentGameExperiment();
experiment -> run();
}
// run() method on the experiment class (simplified)
void Experiments::UniformRandomAgentGameExperiment::run(){
write_header();
// Start maintaining output file in memory, then dump at the end of the experiment
std::string output_str;
output_str.reserve(... a large number I calculate ...);
output_str+="";
// run all the tests
int games_played=0;
while(games_played<n_games){
// Perform an iteration and accumulate results into output_str.
}
// I can verify at this point with simple std::cout that output_str has the content it should
write_experiment(output_str);
}
// write_header() method
void Experiments::UniformRandomAgentGameExperiment::write_header(){
std::ofstream header(Experiments::OUTPUT_DIR + fileheader+".header",std::ios::out | std::ios::trunc); // <- Debugger indicates this line gets visited
header << "Experiment Name: " << experiment_name << std::endl
<< "Experiment Description: " << description << std::endl << std::endl
//... and write some more stuff ... <- Debugger indicates these lines get visited
header.close(); // <- Debugger indicates this line is never reached
}
// write_experiment method
void Experiments::UniformRandomAgentGameExperiment::write_experiment(std::string data){
std::ofstream logfile(Experiments::OUTPUT_DIR + fileheader + ".csv",std::ios::out | std::ios::trunc); // <- Debugger indicates this line gets visited in compiled code
logfile << data; // <- Debugger indicates that this line and the next are skipped in compiled code
logfile.close();
}