【发布时间】:2021-03-03 17:08:02
【问题描述】:
我正在尝试使用来自 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。
在std::filesystem::remove 之前移动pclose(gp); 行可以解决问题,因此看起来gnuplot 确实保存了该文件。同样奇怪的是,如果我手动执行相同操作,我的意思是,我启动 gnuplot,发出相同的命令,而不是退出,我可以使用unlink /tmp/1.png 删除文件。我知道 gnuplot 的 set output 或 unset output 要求,并尝试了这两种变体。
为什么std::filesystem::remove 表现得这么奇怪?
【问题讨论】:
标签: c++ ubuntu gcc gnuplot std-filesystem