在c ++中覆盖文件(不附加)

时间:2014-12-22 21:57:50

标签: c++ file

我需要修改用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;
}

1 个答案:

答案 0 :(得分:3)

popen更改为fopen,将pclose更改为fclosepopen / pclose用于打开/关闭流程。此外,看起来您正在使用标志创建进程。您只需要提供fopen文件路径