如何使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

为什么?在第三次调用中CCD_ 2为真,这意味着文件的所有内容都应该被擦除。

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

最新更新