c - How do I print time in a file at different point of execution by opening the file only at the end? -


i trying print time twice in file. code shown below.

the output not coming correct, printing values not current time is.

the issue have call fprintf only once , @ last. in fact @ last when writing buffer (containing time several getlocaltime calls) file can call fprintf several times, not issue.

i call getlocaltime twice on buffer, seems buffer being overwritten.

can suggest me more elegant way printing time in file @ different points in execution, , opening file once ? (if open file after each getlocaltime function call, adding overhead of file open , write etc. )

latest update: based on suggestion modified code this, , worked

#include "stdafx.h" #include <stdio.h> #include <time.h> #include <windows.h> #include <string.h>   int main() {     systemtime st;      char *buffer;       buffer= (char *)malloc(sizeof(char) * 10000);       getlocaltime(&st);              int offset=0; offset += sprintf(buffer+offset, "time %d,%d, %d, %d \n",st.whour, st.wminute, st.wsecond, st.wmilliseconds); /*other code*/  sleep(1000);  getlocaltime(&st);  offset += sprintf(buffer+offset, "time %d,%d, %d, %d \n",st.whour, st.wminute, st.wsecond, st.wmilliseconds);             file * p;           p=fopen("test.txt","a");           fprintf(p,"%s",buffer);           fclose(p);        return 0; } 

now getting correct results!!

i running code on windows 7 visual studio 2010.

additional info

i cannot use 2 different buffers. reason in actual code printing time 100s of time, have create 100s of buffers, dont want do.

what want this:

getlocaltime();   . . //now put time in buffer @ point . . getlocaltime();  .  . //now put time in buffer @ point . getlocaltime();   . .. //now put time in buffer @ point . . getlocaltime();    . //now put time in buffer @ point    ..   put times several calls  in text file  

ultimately timings in text file

do this

int offset=0; offset += sprintf(buffer+offset, "time %d,%d, %d, %d \n",st.whour, st.wminute, st.wsecond, st.wmilliseconds); /*other code*/ offset += sprintf(buffer+offset, "time %d,%d, %d, %d \n",st.whour, st.wminute, st.wsecond, st.wmilliseconds); 

sprintf returns number of characters printed buffer.

every time call sprintf(), keep updating offset , offset buffer pointer amount next call sprintf(). way first timestamp won't overwritten.


Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -