简体   繁体   English

Linux。 不打印到文件

[英]Linux. Not printing to file

i'm just coding module for HLDS server extension metamod. 我只是HLDS服务器扩展metamod的编码模块。 I wrote a simple utility function for writing logs in format %LOGNAME%_%DATE%.log In windows that function is working fine, but in linux it create file but write nothing. 我编写了一个简单的实用程序函数,用于以%LOGNAME%_%DATE%.log格式编写日志。在Windows中,该函数运行良好,但是在linux中,它创建文件但不写入任何内容。 First I try to search information about that, but I do not found a solution. 首先,我尝试搜索有关此信息,但没有找到解决方案。 I try to fflush file handle, set buffer to _IONBF mode, but nothing is helping. 我尝试使文件句柄模糊,将缓冲区设置为_IONBF模式,但没有任何帮助。 Thank you very much for reading this and helping me with that problem. 非常感谢您阅读本文并帮助我解决该问题。

void UTIL_LogToFile(char* szFileName, const char *fmt, ...)
{
va_list     argptr;
va_start ( argptr, fmt );
vsnprintf ( g_szLogString, sizeof(g_szLogString), fmt, argptr );
va_end   ( argptr );

char* szFilePath = new char[strlen(GlobalVariables::g_szDLLDirPath) + 12 + 30 + 1];
char* szLogFile = get_timestring("_%Y%m%d.log");
sprintf(szFilePath, "%slogs/%s%s", (GlobalVariables::g_szDLLDirPath), szFileName, szLogFile);
FILE* hFile = fopen(szFilePath, "a+");
delete[] szFilePath;
delete[] szLogFile;
if(hFile == NULL)
{
    char szError[256];
    sprintf(szError, "Error fopen: %s\n", strerror(errno));
    SERVER_PRINT(szError);
    clearerr(hFile);
    return;
}

fprintf(hFile, g_szLogString);
if(ferror(hFile))
{
    char szError[256];
    sprintf(szError, "Error fprintf: %s\n", strerror(errno));
    SERVER_PRINT(szError);
    clearerr(hFile);
    return;
}
fclose(hFile);

}

You should only check errno if and only if the previous function failed. 当前一个功能失败时,才应检查errno

If the previous call didn't fail the value of errno is undefined . 如果上一次调用没有失败,则errno的值不确定

So to properly check for errors you must first check if the fopen call returned a null pointer: 因此,要正确检查错误,必须首先检查fopen调用是否返回空指针:

FILE* hFile = fopen(szFilePath, "a+");
if (hFile == nullptr)
{
    perror(szFilePath);
    return;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM