编译后的代码不执行文件写操作

问题描述 投票:0回答:1

我有一个带有run()方法的类,该类应该写一个“标题”文件,执行一些计算,并将计算结果写到一个单独的文件中。我的问题是文件永远不会被写入。 VS代码调试器似乎表明,写入方法中的.close()调用从未实现。即使我尝试使用.flush()方法,该文件也没有写入任何内容。

写入方法调用在Experiments.h中声明的内联变量,该变量在文件中为#included。`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();
}
c++ g++ ofstream
1个回答
0
投票

我发现当我更改Experiments::OUTPUT_DIR = "results/"时(而不是"../results/"时,它写了!

包含main()的代码以及生成的编译后的二进制文件位于项目根目录下的目录中,我假设我需要指定一个相对于其的路径。我错了-路径显然与调用已编译二进制文件的位置有关(或者可能是从哪里编译的?idk)。

因此,在进行此更改之前,我猜编译器已经看到它正在尝试写入不存在的位置"project_root/../results",并试图完全跳过它。

© www.soinside.com 2019 - 2024. All rights reserved.