ofstream不会将缓冲区写入文件 [英] ofstream doesn't write buffer to file

查看:942
本文介绍了ofstream不会将缓冲区写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将buf指针的内容写入由stream创建的文件。

I'm trying to write the contents of buf pointer to the file created by ofstream.

由于某种原因,文件为空,但buf的内容从不空白...我做错了什么?

For some reason the file is empty, however the contents of buf is never empty... What am I doing wrong?

void DLog::Log(const char *fmt, ...)
{
    va_list varptr;

    va_start(varptr, fmt);

    int n = ::_vscprintf(fmt, varptr);
    char *buf = new char[n + 1];
    ::vsprintf(buf, fmt, varptr);

    va_end(varptr);

    if (!m_filename.empty())
    {

        std::ofstream ofstr(m_filename.c_str(), ios::out);

        ofstr << *buf; // contents of *buf are NEVER empty, however nothing is in file??

        ofstr.close();
    }


    delete [] buf;
}


推荐答案

摆脱毛茸茸的东西,像手动分配管理。

Many problems can be solved by getting rid of the hairy stuff, like manual allocation management.

不要在您的代码中使用 new T [N] ,而应使用 std ::向量< T> v(N); 。这个单独的可以解决你的问题,因为指针的东西不是这样的:

Never use new T[N] in your code: instead use std::vector<T> v(N);. Simply this alone might solve your problem, because the pointer stuff isn't in the way:

void DLog::Log(const char *fmt, ...)
{
    va_list varptr;
    va_start(varptr, fmt);

    int n = ::_vscprintf(fmt, varptr);
    std::vector<char> buf(n + 1);

    ::vsprintf(&buf[0], fmt, varptr);

    va_end(varptr);

    if (!m_filename.empty())
    {
        std::ofstream ofstr(m_filename.c_str(), ios::out);
        if (!ofstr) 
        {
            // didn't open, do some error reporting here
        }

        // copy each character to the stream
        std::copy(buf.begin(), buf.end(), std::ostream_iterator<char>(ofstr));

        // no need to close, it's done automatically
    }

    // no need to remember to delete
}

更易于阅读和维护。注意更好的是一个 std :: string buf(n + 1); ,那么你可以只做 ofstr< buf; 。很遗憾, std :: string 目前不需要连续存储它的元素,例如 std :: vector 。这意味着& buf [0] 的行不能保证工作。也就是说,我怀疑你会发现一个实现,它不会工作。

Much easier to read and maintain. Note even better would be a std::string buf(n + 1);, then you could just do ofstr << buf;. Sadly, std::string isn't currently required to store its elements contiguously, like std::vector. This means the line with &buf[0] isn't guaranteed to work. That said, I doubt you'll find an implementation where it wouldn't work. Still, it's arguably better to maintain guaranteed behavior.

我会可疑 issue 是你解除引用指针。

I do suspect the issue was you dereferencing the pointer, though.

这篇关于ofstream不会将缓冲区写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆