我正在尝试使用来自 C++ 应用程序的 gnuplot,gcc 版本 9.3.0(Ubuntu 9.3.0-17ubuntu1~20.04)。我遇到了关于打印到文件的奇怪行为。
因此,可重现的示例是:
#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;
}
输出是(很奇怪):
unsuccesfully: 0 Success
会发生什么:gnuplot 成功地将有效的 png 文件写入所需的目的地。但是,std::filesystem::remove不会删除文件,返回false
并(因此)打印有关成功的神秘消息,错误代码为 0。在解决问题pclose(gp);
之前移动行std::filesystem::remove
,因此看起来 gnuplot 确实保存了文件。奇怪的是,如果我手动执行相同操作,我的意思是,我启动 gnuplot,发出相同的命令,而不是退出,我可以使用unlink /tmp/1.png
. 我知道 gnuplot 的set output
或unset output
要求,并尝试了这两种变体。
为什么std::filesystem::remove
行为如此奇怪?