fstream 不会打印到文件
以下代码会将某些内容打印到文件中
std::fstream fout ("D_addr.txt", std::fstream::app);
fout << pkt->Addr() << std::endl;
flush(fout);
fout.close();
在调试时,我观看了 pkt->Addr()
并且它有一些值。 fout
行顺利通过。此外,还会创建文件 D_addr.txt
。但是关闭文件后,文件大小为零!没有写入任何内容。
问题出在哪里?
The following code will print something to a file
std::fstream fout ("D_addr.txt", std::fstream::app);
fout << pkt->Addr() << std::endl;
flush(fout);
fout.close();
While debugging, I watched pkt->Addr()
and it has some values. The fout
line is passed without problem. Also the file D_addr.txt
is created. However after closing the file, the file size is zero! nothing has been written to it.
Where is the problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我猜这不是您的实际代码,如果是,我将从您的
Addr()
函数开始。请注意,fstream::close “关闭当前与对象,将其与流解除关联。任何挂起的输出序列都会写入物理文件。”
flush(fout);
可以省略。您还应该指定
std::fstream::out
标志。 “如果使用该参数中的任何值调用该函数,则默认模式将被覆盖,而不是组合。”因此,您应该传递std::fstream::app
而不是std::fstream::app
代码>std::fstream::app | std::fstream::out。This is not your actual code I guess and if it is I would start with that
Addr()
function of yours.Note that fstream::close "closes the file currently associated with the object, disassociating it from the stream. Any pending output sequence is written to the physical file."
flush(fout);
can be omitted.You should also specify
std::fstream::out
flag. "If the function is called with any value in that parameter the default mode is overridden, not combined." So instead ofstd::fstream::app
you should passstd::fstream::app | std::fstream::out
.我想知道您是否使用了错误的类。如果要写入文件,请使用
std::ofstream
,而不是std::fstream
。特别是,std::ofstream
的构造函数在调用rdbuf()->open
时强制使用ios_base::out
位;std::fstream
的构造函数没有(因此您打开的文件既没有读也没有写访问权限)。您可能想检查错误状态:打开是否成功,关闭(或刷新)后,所有写入是否成功。通常的做法是:
在 open (构造函数)之后,您可以使用
fout.is_open()
,它的优点是对于您的内容更加明确检查.I'm wondering if you're not using the wrong class. If you want to write to a file, use
std::ofstream
, and notstd::fstream
. In particular, the constructor ofstd::ofstream
forces theios_base::out
bit when callingrdbuf()->open
; the constructor ofstd::fstream
doesn't (so you're opening the file with neither read nor write access).And you probably want to check the error status: did the open succeed, and after the close (or the flush), did all of the writes succeed. The usual way of doing this is just:
After the open (the constructor), you can use
fout.is_open()
, which has the advantage of being a little bit more explicit with regards to what you are checking for.首先,
flush()
和fout.close()
不会造成任何伤害,但这里不需要,因为当fout
获取时销毁的文件将作为 fstream 析构函数的一部分被关闭(并刷新)。其次,您应该使用
ofstream
或将标记std::ios::out
添加到openmode
参数。尝试一些类似的事情:
First of all,
flush()
andfout.close()
do not make any harm, but are not needed here, because whenfout
gets destroyed the file will be closed (and flushed) as part offstream
destructor.Second, you should use an
ofstream
or alternatively add the flagstd::ios::out
to theopenmode
parameter.Try something along the lines of: