【问题标题】:Why does this write() operation just write a single line为什么这个 write() 操作只写一行
【发布时间】:2012-06-04 13:04:39
【问题描述】:

下面的代码有一个小问题。我在课堂上从状态机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 指的是 write、binary 和 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);
            }
        }
    }

【问题讨论】:

  • 好像你忘了在 write_file() 结束时调用 cogra_ieee_802_15_4_sink::close() 方法。
  • O_TRUNC 设置文件大小为0字节
  • 每次调用cogra_ieee_802_15_4_sink::write_file 时都使用O_TRUNC 打开文件,将文件截断为零长度,然后写入一行。你很惊讶文件中只有一行吗?
  • jepp,今天早上我好像把 O_TRUNC 和 O_APPEND 搞混了。谢谢:)

标签: c++ linux file csv append


【解决方案1】:

O_TRUNC 的描述来自man open

如果文件已经存在并且是常规文件并且打开​​模式允许写入(即O_RDWR或O_WRONLY),它将被截断为长度0。如果文件是FIFO或终端设备文件,则O_TRUNC标志为忽略。否则不指定 O_TRUNC 的效果。

文件在每次调用write_file() 时打开,删除之前写入的任何内容。将O_TRUNC 替换为O_APPEND

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-08
    相关资源
    最近更新 更多