C++ 如何使open()替换文件内容?
请注意,这非常重要,任何想法都非常感谢。这件事我已经坚持了好几天了 更新:C++ 如何使open()替换文件内容?,c++,file,C++,File,请注意,这非常重要,任何想法都非常感谢。这件事我已经坚持了好几天了 更新: 我添加了一些注释以使事情更清楚 您可以在以下位置运行相同的代码: 我在C++中写了以下函数,我调用3次来打开文件并写到: #include <unistd.h> #include <stdexcept> #include <iostream> #include <sstream> #include <sys/fcntl.h> using namespac
我在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");
}
}
为什么呢?在第三次调用中,single_red为true,这意味着文件的所有内容都应该被擦除
O_WRONLY-表示以只写模式打开文件
O_create-如果文件不存在,则创建它
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
O_APPEND
意味着它将在当前内容的末尾开始写入,因此不会覆盖它。添加O_TRUNC
标志以截断现有内容。@bar如果single_red为真,我不使用O_APPEND,则它将覆盖,但是不要删除任何内容。因此,如果文件包含abc
,然后你写d
,你会得到dbc
OP在@me\u go中回复。如果这不能解决问题,你需要发布一个证明。OP的回复不可信。这个解决方案会奏效。我们不能指望如此到处追逐重复的帖子@雷米尔博
int flags = O_WRONLY | O_CREAT | (single_red ? O_TRUNC : O_APPEND);
file_fd = (single_red) ? open("test.txt", flags, 0666); //open file