程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了如何使 open() 替换文件内容?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决如何使 open() 替换文件内容??

开发过程中遇到如何使 open() 替换文件内容?的问题如何解决?下面主要结合日常开发的经验,给出你关于如何使 open() 替换文件内容?的解决方法建议,希望对你解决如何使 open() 替换文件内容?有所启发或帮助;

请这真的很重要,任何想法都非常感谢。我已经坚持了好几天了。

更新:

  1. 我添加了一些注释来使事情清楚。

  2. 您可以在此处运行相同的代码:https://onlinegdb.com/HyYP3qguu


我用 C++ 编写了以下函数,我调用了 3 次来打开一个文件并写入它:

#include <unistd.h>
#include <stdexcept>
#include <iostream>
#include <sstream>
#include <sys/fcntl.h>

using namespace std;

bool try_num=0;

voID cmd_execute()
{
    bool single_red = true;
    if (try_num==1) single_red=false;
    try_num++; // global variable starts from 0

    int file_fd,redirect_fd1,redirect_fd2;

    file_fd = (single_red) ? open("test.txt",O_WRONLY | O_CREAT,0666) :
    open("test.txt",O_WRONLY | O_CREAT | O_APPEND,0666); //open file
    
    if (file_fd < 0)
    {
        perror("smash error: open Failed");
        return;
    }
    redirect_fd1 = dup(1); // duplicate standard output
    if (redirect_fd1 < 0)
    {
        perror("smash error: dup Failed");
        return;
    }
    redirect_fd2 = dup2(file_fd,1); // replace standard output with file
    if (redirect_fd2 < 0)
    {
        perror("smash error: dup2 Failed");
        return;
    }
    if (close(file_fd) < 0)//close the other file
    {
        perror("smash error: close Failed");
        return;
    }
    cout << "Hello" << endl;
    /** end **/
    if (dup2(redirect_fd1,1) < 0)//close file and replace by standard output
    {
        perror("smash error: dup2 Failed");
        return;
    }
    if (close(redirect_fd1) < 0)//close the other standard output
    {
        perror("smash error: close Failed");
    }
}

当我打开文件 test.txt 时,我看到:

Hello
Hello

这是为什么?在第三个调用中 single_red 为真,这意味着应该删除文件的所有内容。

O_WRONLY - 表示以只写模式打开文件。

O_CREAT - 如果文件不存在,则创建它。

O_APPEND - 将文本附加到文件末尾。

解决方法

如果要替换文件内容,请使用 O_TRUNC。否则它将覆盖该文件,但不会删除其中已有的任何内容。如果您写入的长度小于现有长度,您将看到新内容后跟原始内容的其余部分。

    int flags = O_WRONLY | O_CREAT | (single_red ? O_TRUNC : O_APPEND);
    file_fd = (single_red) ? open("test.txt",flags,0666); //open file

大佬总结

以上是大佬教程为你收集整理的如何使 open() 替换文件内容?全部内容,希望文章能够帮你解决如何使 open() 替换文件内容?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。