gpt4 book ai didi

c++ - 为什么这个 write() 操作只写一行

转载 作者:太空宇宙 更新时间:2023-11-04 05:06:07 27 4
gpt4 key购买 nike

我的代码有一个小问题,如下所示。我在我的类中从状态机 this->write_file(this->d_filename); 中调用它。循环中的情况会遇到几次,但是我想要生成的 CSV 文件中只有一行条目。

我不知道这是为什么。我在写入函数中使用 this->open(filename) 打开文件。它返回文件描述符。该文件使用 O_TRUNK 和 if ((d_new_fp = fdopen(fd, d_is_binary ? "wba": "w")) == NULL) 打开。而aba指的是写入、二进制和 append 。因此我预计不止一行。

fprintf 语句写入我的数据。它还具有 \n

 fprintf(d_new_fp, "%s, %d %d\n", this->d_packet, this->d_lqi, this->d_lqi_sample_count);

我根本不明白为什么我的文件没有增长。

最好,马吕斯

 inline bool
cogra_ieee_802_15_4_sink::open(const char *filename)
{
gruel::scoped_lock guard(d_mutex); // hold mutex for duration of this function

// we use the open system call to get access to the O_LARGEFILE flag.
int fd;
if ((fd = ::open(filename, O_WRONLY | O_CREAT | O_TRUNC | OUR_O_LARGEFILE,
0664)) < 0)
{
perror(filename);
return false;
}

if (d_new_fp)
{ // if we've already got a new one open, close it
fclose(d_new_fp);
d_new_fp = 0;
}

if ((d_new_fp = fdopen(fd, d_is_binary ? "wba" : "w")) == NULL)
{
perror(filename);
::close(fd);
}

d_updated = true;
return d_new_fp != 0;
}

inline void
cogra_ieee_802_15_4_sink::close()
{
gruel::scoped_lock guard(d_mutex); // hold mutex for duration of this function

if (d_new_fp)
{
fclose(d_new_fp);
d_new_fp = 0;
}
d_updated = true;
}

inline void
cogra_ieee_802_15_4_sink::write_file(const char* filename)
{
if (this->open(filename))
{

fprintf(d_new_fp, "%s, %d %d\n", this->d_packet, this->d_lqi,
this->d_lqi_sample_count);
if (true)
{
fprintf(stderr, "Writing file %x\n", this->d_packet);
}
}
}

最佳答案

来自 man openO_TRUNC 说明:

If the file already exists and is a regular file and the open mode allows writing (i.e., is O_RDWR or O_WRONLY) it will be truncated to length 0. If the file is a FIFO or terminal device file, the O_TRUNC flag is ignored. Otherwise the effect of O_TRUNC is unspecified.

每次调用 write_file() 时都会打开该文件,删除之前写入的所有内容。将 O_TRUNC 替换为 O_APPEND

关于c++ - 为什么这个 write() 操作只写一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10813857/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com