How to write a file in Cling non-interactive mode

Cling Version: 1.0 dev
Platform: Ubuntu Linux 20.04.1
Compiler: gcc (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0


Hi,
I’d like to be able to do file io running Cling in non-interactive mode.

Running interactively, given the file test3.cpp which contains:

#include <iostream>
#include <fstream>
#include <string>

// Function that returns the square of the number.
int sq_num(int num) {
    return num * num;
}

// Write to file
void write_file(std::string file_name, int num) {

    FILE* out_file = fopen(file_name.c_str(), "w");
    if(!out_file) {
        std::cerr << "\nCannot open file named: " << file_name << ".\n\n";
        exit (EXIT_FAILURE);
    }

    fprintf(out_file, "Number = %d", num);
    fclose(out_file);
}

void test3() {
    int i = sq_num(11);
    write_file("foobar.txt", i);
}

Cling creates the file foobar.txt containing “Number = 121”.

****************** CLING ******************
* Type C++ code and press enter to run it *
*             Type .q to exit             *
*******************************************
[cling]$ .x test3.cpp
[cling]$ .q

But if I add “#! test3.cpp” as the first line of test3.cpp and run it non-interactively:

$ ../obj/bin/cling test3.cpp

There are no errors or warnings, but the foobar.txt file is not created. Is there an option or setting that would allow this to work?

Thanks,

Gene

Hi,

The shebang approach will work if you have a statement calling the function test3. Maybe in the end of the file add test3();

Best, Vassil

Yes, that worked. Thank you Vassil.