我需要修改用c ++编写的代码。代码打开文件authfile
并向其写入49个字节。如果文件已经存在,我需要确保覆盖现有数据。
原始代码首先删除了该文件,然后创建了一个新文件。出于讨论之外的原因,我无法删除该文件,在向其写入新数据之前,我只需要确保它是空的。
下面是写入数据的函数。如何修改它,以便覆盖文件的内容?
我想,我需要改变popen的选项
bool Util::add_mcookie(const std::string &mcookie, const char *display,
const std::string &xauth_cmd, const std::string &authfile)
{
FILE *fp;
std::string cmd = xauth_cmd + " -f " + authfile + " -q";
fp = popen(cmd.c_str(), "w");
if (!fp)
return false;
fprintf(fp, "remove %s\n", display);
fprintf(fp, "add %s %s %s\n", display, ".", mcookie.c_str());
fprintf(fp, "exit\n");
pclose(fp);
return true;
}
答案 0 :(得分:3)
将popen
更改为fopen
,将pclose
更改为fclose
。 popen
/ pclose
用于打开/关闭流程。此外,看起来您正在使用标志创建进程。您只需要提供fopen
文件路径