I'm trying to use gnuplot from C++ application, gcc version 9.3.0 (Ubuntu 9.3.0-17ubuntu1~20.04). I've encountered strange behavior concerning plotting to files.
So, the reproducible example is:
#include <iostream>
#include <filesystem>
int main()
{
// whatever valid filename
std::string name1 = "/tmp/1.png";
// open gnuplot pipe
auto gp = popen("gnuplot", "w");
// plot sin(x) to file. Note "unset output" in the end.
std::string cmd="set term png\nset output '"+name1+"'\nplot sin(x)\nunset output\n";
// send the command to gnuplot
fwrite(cmd.c_str(), sizeof(char), cmd.length(), gp);
std::error_code ec;
// removing the file
if (!std::filesystem::remove(name1, ec))
std::cout<<"unsuccesfully: "<<ec.value()<<"\s"<<ec.message()<<"\n";
pclose(gp);
return 0;
}
The output is (very strange):
unsuccesfully: 0 Success
What happens: gnuplot successfully writes a valid png file to desired destination. However, std::filesystem::remove does not remove the file, returns false
and (therefore) prints cryptic message about success with error code 0.
Moving pclose(gp);
line before std::filesystem::remove
solves the problem, so it does look like gnuplot holds the file. What is also strange that if I do the same manually, I mean, I launch gnuplot, issue the same command, and not exit, I'm able to remove the file with unlink /tmp/1.png
. I'm aware about gnuplot's set output
or unset output
requirement, and tried both variants.
Why the std::filesystem::remove
acts this strange?