i'm just coding module for HLDS server extension 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. 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. 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.
If the previous call didn't fail the value of errno
is undefined .
So to properly check for errors you must first check if the fopen
call returned a null pointer:
FILE* hFile = fopen(szFilePath, "a+");
if (hFile == nullptr)
{
perror(szFilePath);
return;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.