如何使open()替换文件内容? [英] How to make open() replace file contents?

查看:68
本文介绍了如何使open()替换文件内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Please this is really important, any ideas are VERY appreciated. I have been stuck on this for days.

更新:

  1. 我添加了一些注释以使事情变得清楚.

  1. I have added some notes to make things clear.

您可以在以下位置运行相同的代码: https://onlinegdb.com/HyYP3qguu

You can run the same code here on: https://onlinegdb.com/HyYP3qguu


我在C ++中编写了以下函数,该函数调用3次以打开文件并将其写入:


I wrote the following function in C++ which I call 3 times to open a file and writes to it:

#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 时,我看到:

When I open my file test.txt I see:

Hello
Hello

那是为什么?在第三次调用中, single_red 为true,这意味着应擦除文件的所有内容.

why is that? in the third call single_red is true which means all contents of file should be erased.

O_WRONLY-表示以只读模式打开文件.

O_WRONLY - means open file in write only mode.

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

O_CREAT - if file doesn't exist then create it.

O_APPEND-在文件末尾附加文本.

O_APPEND - append text to end of file.

推荐答案

如果要替换文件内容,请使用 O_TRUNC .否则它将覆盖文件,但不会删除其中已有的文件.如果您写的字数少于现有长度,则会看到新内容,然后是其余的原始内容.

Use O_TRUNC if you want to replace the file contents. Otherwise it will overwrite the file, but not remove whatever is already in it. If you write less than the existing length, you'll see the new contents followed by the remainder of the original contents.

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

这篇关于如何使open()替换文件内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆