2012-05-30 16 views
-1

我在下面的代碼中遇到了一個小問題。我在國家機器this->write_file(this->d_filename);內的課堂上稱它。循環中的情況經歷了幾次,但是我只想在我想生成的CSV文件中有一行條目。爲什麼這個write()操作只寫一行

我不知道這是爲什麼。我在我的寫入功能中用this->open(filename)打開文件。它返回文件描述符。該文件用O_TRUNK和if ((d_new_fp = fdopen(fd, d_is_binary ? "wba" : "w")) == NULL)打開。而aba指的是寫入,二進制和追加。因此我期望不止一行。

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); 
      } 
     } 
    } 
+1

似乎忘記了在write_file()的末尾調用cogra_ieee_802_15_4_sink :: close()方法。 – ismail

+1

'O_TRUNC'將文件大小設置爲0字節 – hmjd

+0

每次調用'cogra_ieee_802_15_4_sink :: write_file'時,都會用'O_TRUNC'打開文件,將文件截斷爲零,然後寫入一行。你很驚訝,你只能得到一個文件中的一行? –

回答

1

描述爲O_TRUNCman open

如果該文件已經存在,並且是一個普通文件和開放模式允許寫入(即是O_RDWR或O_WRONLY )它將被截斷爲長度0.如果文件是FIFO或終端設備文件,則忽略O_TRUNC標誌。否則,O_TRUNC的效果未指定。

該文件在每次調用打開write_file(),刪除以前寫過什麼。將O_TRUNC替換爲O_APPEND

相關問題