|
-
March 9th, 2015, 08:40 AM
#1
File opening and closing after 24 hours
hello,
We are using a file operation for logging the data, file should be closed after the 24 hrs from the time the file is opened and open the new file for the current date.
Issue:
How to close the file after 24 hrs and create the new file ,please look into the code and provide me if any solution or suggest.
Code:
//Header files
#include<time.h>
#include<string.h>
#include<stdio.h>
#include<windows.h>
#define LG_UPS_BB 100
#define LG_TCU_TEMP 200
// Global variables.
FILE *g_dlLogFile ; //!< File pointer to store the data logging file handler.
CRITICAL_SECTION g_dlCriticalSection ; //!< Critical section object.
int d_dlLastSNo = 0 ;
HANDLE d_hdlDataLog ;
DWORD d_tidDataLog ;
int d_upBattery = 20 ;
int d_tcuTemp = 24 ;
// Functions
void dlHandler(void *pParam) ;
int dlInitialize(void)
{
time_t u32Time ; // Variable to store the current time.
char strFileName[50] ; // File name to log the data.
struct tm stTime ; // Structure name to store the time.
///Step1: Initialize a critical section object.
InitializeCriticalSection(&g_dlCriticalSection) ;
///Step2: Log file initialized to NULL.
g_dlLogFile = NULL ;
///Step3: Reading system current time.
u32Time = time(NULL) ;
stTime = *(localtime(&u32Time)) ;
///Step4: Generating the log file name.
sprintf(strFileName, "%d%02d%02d_s%02d", (stTime.tm_year + 1900), (stTime.tm_mon + 1), stTime.tm_mday, d_dlLastSNo) ;
///Step5: Open the log file for data logging.
g_dlLogFile = fopen(strFileName, "w") ;
if (g_dlLogFile == NULL)
{
printf ("\nDL: File not created , errno = %d", GetLastError()) ;
}
///Step7: Creating the thread.
d_hdlDataLog = CreateThread(NULL, 0, (void*)dlHandler, 0, 0, &d_tidDataLog) ;
if(d_hdlDataLog == NULL)
{
printf ("\nDL: Thread creation failed, errno = %d", GetLastError()) ;
}
///Step8: Return the status.
return 0;
}
int dlSetLogID(int pId)
{
BOOL bStatus = -1 ; // Hold the status for PostThreadMessage.
///Step1: Wait for the ownership of the critical section object.
EnterCriticalSection(&g_dlCriticalSection) ;
///Step2: Send the log id to the buffer.
bStatus = PostThreadMessageA(d_tidDataLog, (WM_USER + pId), 0, 0) ;
///Step3: Report error in message posted and return FALSE.
if (bStatus == FALSE)
{
printf ("\nDL: Message is not posted in the buffer, errno = %d", GetLastError()) ;
}
///Step4: Release the ownership of the critical section object.
LeaveCriticalSection(&g_dlCriticalSection) ;
///Step5: Return the status.
return 0;
}
void dlHandler(void *pParam)
{
MSG stMsg ; // Pointer to the message structure
BOOL bStatus = FALSE ; // bStatus to hold the return value for PostMessage.
unsigned int iLogNo = 0 ; // For serial numbers in the log file.
time_t u32Time ; // To store the current time.
struct tm stTime ; // Structure name to store the time.
char strFileName[20] ;
if(g_dlLogFile == NULL)
{
#ifdef DEBUG_DATA_LOG
printf ("\nDL: Log file pointer is invalid, errno = %d", errno) ;
#endif
}
// Loop to log the record.
while(1)
{
// Wait until the message is received.
WaitMessage() ;
///Step1: Retrieves the message from the buffer.
bStatus = GetMessageA(&stMsg, NULL, 0, 0) ;
if(bStatus == -1)
{
printf ("\nDL: Message is not retrieved from the buffer, errno = %d", GetLastError()) ;
}
else
{
///Step4: Get the system time.
u32Time = time(NULL) ;
stTime = *(localtime(&u32Time) );
// Increment the Log Numbers for each record.
iLogNo++ ;
///Step5: Store the log no, system time, mode of operation and log id in the file.
fprintf(g_dlLogFile,"\n%d,%d:%d:%d,%d", iLogNo, stTime.tm_hour, stTime.tm_min,
stTime.tm_sec, (stMsg.message-WM_USER)) ;
///Step6: For storing the data in the file.
switch((stMsg.message - WM_USER))
{
case LG_UPS_BB:
{
//Battery backup value stored in the file.
fprintf(g_dlLogFile,",%u", d_upBattery);
break;
}
case LG_TCU_TEMP:
{
//Temperature value is stored in the file.
fprintf(g_dlLogFile,",%.02f", d_tcuTemp);
break;
}
default:
break;
}
}
Sleep(100) ;
}
}
int dlClose()
{
///Step1: Close the Log file pointer.
if(g_dlLogFile != NULL)
fclose(g_dlLogFile) ;
///Step2: Delete the critical section object.
DeleteCriticalSection(&g_dlCriticalSection) ;
///Step3: Close the thread handle.
if(d_hdlDataLog != NULL)
CloseHandle(d_hdlDataLog) ;
///Step4: Return the status.
return 0;
}
int main ()
{
dlInitialize(void) ;
dlSetLogID(LG_UPS_BB) ;
return 0 ;
}
-
March 9th, 2015, 12:41 PM
#2
Re: File opening and closing after 24 hours
Have a global variable the time the file is opened (u32Time in dlInitialize()). Have another variable (eg startTime24) set 24 hours from this date (ie add 60 * 60 * 24 (86400) to the current time). In dlHandler when you get the current system time, compare it to the value of startTime24 and if the current time is greater then this then close the current file and open another. Update startTime24 to the current time + 24 hours (add 86400 to it).
All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!
C++23 Compiler: Microsoft VS2022 (17.6.5)
-
March 9th, 2015, 05:54 PM
#3
Re: File opening and closing after 24 hours
Another option is to use a logging framework that does this for you already.
With regard to your code, if more than one instance of the program is logging to the same log file, a critical section isn't sufficient to synchronize access to the log file.
-
March 11th, 2015, 03:06 AM
#4
Re: File opening and closing after 24 hours
In the "Loop to log the record" right after WaitMessage() you test current system time against log file creation time. In case the time span is longer than 24 hrs, the file gets closed, and another log file created. Typically there's no sense in being super-nano-precise in catching the moment of 24 hrs elapsing.
Best regards,
Igor
-
March 12th, 2015, 04:07 PM
#5
Re: File opening and closing after 24 hours
 Originally Posted by Jeevan Rudramurthy
We are using a file operation for logging the data, file should be closed after the 24 hrs from the time the file is opened and open the new file for the current date.
The requirement to close the log "after the 24 hrs from the time the file is opened" is strange. I would suggest to close it (and create a new one) at midnight, so that the file name actually matches the date its records were written. You can use some kind of a timer to send another message to your thread every midnight. Or just check if the current timestamp rolled over midnight.
Vlad - MS MVP [2007 - 2012] - www.FeinSoftware.com
Convenience and productivity tools for Microsoft Visual Studio:
FeinWindows - replacement windows manager for Visual Studio, and more...
-
March 12th, 2015, 04:37 PM
#6
Re: File opening and closing after 24 hours
 Originally Posted by VladimirF
The requirement to close the log "after the 24 hrs from the time the file is opened" is strange.
Hopefully, the OP is referring to some end of file data, like a summary, rather than keeping the actual file handle open for 24 hours.
-
March 13th, 2015, 03:26 AM
#7
Re: File opening and closing after 24 hours
 Originally Posted by VladimirF
The requirement to close the log "after the 24 hrs from the time the file is opened" is strange. I would suggest to close it (and create a new one) at midnight, so that the file name actually matches the date its records were written.
Well, the policy of attending logs may differ from project to project, in fact, it's up to Customer...
PS ...but I would consider the midnight log closure be the same strange as the 24hrs one. 
PPS. In one of my enterprise-level projects the policy was to limit the particular log chunk size and put a timestamp of closing into the name. Some time passed, the policy was reasonably added with log compression rule (like keep logs uncompressed only for N days/weeks). I would say that for 24/7 software the control over log size is much more important than splitting by time. To the moment I support the product for a decade, and never had any issue with analyzing logs not split by some time-dependent rule. Of course, the log itself includes timestamps for the records.
Best regards,
Igor
-
March 13th, 2015, 09:15 AM
#8
Re: File opening and closing after 24 hours
 Originally Posted by Igor Vartanov
PS ...but I would consider the midnight log closure be the same strange as the 24hrs one. 
It most certainly is not the same strange The stated 24hrs periodicity implies correlation with date.
 Originally Posted by Igor Vartanov
PPS. In one of my enterprise-level projects the policy was to limit the particular log chunk size and put a timestamp of closing into the name. Some time passed, the policy was reasonably added with log compression rule (like keep logs uncompressed only for N days/weeks). I would say that for 24/7 software the control over log size is much more important than splitting by time. To the moment I support the product for a decade, and never had any issue with analyzing logs not split by some time-dependent rule. Of course, the log itself includes timestamps for the records.
Agree with everything. As was suggested above, most decent logging libraries include chunking. However, I do like when large logs are split on the date as well (unless many days will fit in one chink). I mean, if the logs are split almost by the date (like in OP's request), I'd rather enforce date-line splitting. I found that clients sometime have no understanding of the file structure, and getting a log that you need causes unneeded aggravation (on both sides).
Vlad - MS MVP [2007 - 2012] - www.FeinSoftware.com
Convenience and productivity tools for Microsoft Visual Studio:
FeinWindows - replacement windows manager for Visual Studio, and more...
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|