C++ Windows 2008 Server 上的 fputs 断言
在下面的代码中,fputs(...) 在 Windows Server 2008 上运行时抛出一个断言。我在 Vista 或 XP 计算机上没有这个问题。我不知道是什么原因造成的?
断言是: Stream != NULL
它似乎也是随机的,因为有时它似乎成功......随着日志文件的创建。
有人可以帮忙吗?
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())
{
FILE *f = fopen(m_filename.c_str(), "at");
if (f != NULL)
{
fputs(buf, f);
fputs("\n", f);
fclose(f);
}
else
::MessageBox(0,"Error at fputs in Log","Error",0);
}
delete [] buf;
}
In the below code the fputs(...) throws an assert when running on Windows Server 2008. I don't have this problem on a Vista or XP machine. I'm at a loss as to what is causing it?
The assert is: Stream != NULL
It seems to be random too, as sometimes it seems to succeed... as the log files get created.
Can anybody help?
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())
{
FILE *f = fopen(m_filename.c_str(), "at");
if (f != NULL)
{
fputs(buf, f);
fputs("\n", f);
fclose(f);
}
else
::MessageBox(0,"Error at fputs in Log","Error",0);
}
delete [] buf;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是断言的第二个
fputs
吗?您的vsprintf
是否可能超出缓冲区的末尾?您的格式字符串和实际的可变参数可能不正确匹配。您的问题被标记为 C++,并且肯定有更好的方法可以用该语言来做到这一点。
至少考虑使用
std::ofstream
来代替旧的 CFILE*
API 进行编写。但更好的方法是完全忘记 varargs 函数并使用像 C++ 标准流这样的插入运算符。然后,您将获得类型安全性并消除容易错误传递的可变参数的需要。Is it the second
fputs
that's asserting? Is it possible yourvsprintf
is overrunning the end of your buffer? Your format string and actual varargs may not match correctly.Your question is tagged C++ and there are definitely better ways to do this in that language.
At least consider using
std::ofstream
to do your writing instead of the old CFILE*
API. But better still is to forget the varargs function completely and using an insertion operator like the C++ standard streams. Then you get type safety and remove the need for easily mis-passed varargs parameters.