tags:

views:

184

answers:

4

I want to create a series of files under "log" directory which every file named based on execution time. And in each of these files, I want to store some log info for my program like the function prototype that acts,etc. Usually I use the hard way of fopen("log/***","a") which is not for this purpose.And I just write a timestamp function:

char* timeStamp(char* txt){
  char* rc;
  char timestamp[16];
  time_t rawtime = time(0);
  tm *now = localtime(&rawtime);

  if(rawtime != -1) {
     strftime(timestamp,16,"%y%m%d_%H%M%S",now);
     rc = strcat(txt,timestamp);
  }
  return(rc);
}

But I don't know what to do next. Please help me with this!

+3  A: 

Declare a char array big enough to hold 16 + "log/" (so 20 characters total) and initialize it to "log/", then use strcat() or something related to add the time string returned by your function to the end of your array. And there you go!

Note how the string addition works: Your char array is 16 characters, which means you can put in 15 characters plus a nul byte. It's important not to forget that. If you need a 16 character string, you need to declare it as char timestamp[17] instead. Note that "log/" is a 4 character string, so it takes up 5 characters (one for the nul byte at the end), but strcat() will overwrite starting at the nul byte at the end, so you'll end up with the right number. Don't count the nul terminator twice, but more importantly, don't forget about it. Debugging that is a much bigger problem.

EDIT: While we're at it, I misread your code. I thought it just returned a string with the time, but it appears that it adds the time to a string passed in. This is probably better than what I thought you were doing. However, if you wanted, you could just make the function do all the work - it puts "log/" in the string before it puts the timestamp. It's not that hard.

Chris Lutz
thank you very much!
iBacchus
+1  A: 

Sounds like you have mostly solved it already - to create a file like you describe:

char filename[256] = "log/";
timeStamp( filename );
f = fopen( filename, "a" );

Or do you wish do do something more?

Timothy Pratley
Why not just `char filename[256] = "log/";` ?
Chris Lutz
change to use snprintf, strncat and friends and I'll give you a +1. Lets not encourage buffer overflows
Isak Savo
Thanks, you are correct.
Timothy Pratley
+1  A: 
Sauron
+1  A: 

What about this:

#include <stdio.h>
#include <time.h>

#define LOGNAME_FORMAT "log/%Y%m%d_%H%M%S"
#define LOGNAME_SIZE 20

FILE *logfile(void)
{
    static char name[LOGNAME_SIZE];
    time_t now = time(0);
    strftime(name, sizeof(name), LOGNAME_FORMAT, localtime(&now));
    return fopen(name, "ab");
}

You'd use it like this:

FILE *file = logfile();
// do logging
fclose(file);

Keep in mind that localtime() is not thread-safe!

Christoph