【发布时间】: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 搞混了。谢谢:)