I have an issue with inserting time in a text file. I use the following code and i get |21,43,1,3,10,5| Wed Feb 01 20:42:32 2012
which is normal but what i WANT TO DO is place the time before the numbers for example like Wed Feb 01 20:42:32 2012 |21,43,1,3,10,5|
However, i cant do so cause when i use the fprintf with ctime function before fprintf the numbers it recognizes the \n within ctime and so it changes line 1st and then printing the numbers. It goes like:
Wed Feb 01 20:42:32 2012
|21,43,1,3,10,5|
which is something that i dont want... How can i fprintf the time without swiching to the next line in the text??? Thanks in advance!
fprintf(file," |");
for (i=0;i<6;i++)
{
buffer[i]=(lucky_number=rand()%49+1); //range 1-49
for (j=0;j<i;j++)
{
if (buffer[j]==lucky_number)
i--;
}
itoa (buffer[i],draw_No,10);
fprintf(file,"%s",draw_No);
if (i!=5)
fprintf(file,",");
}
fprintf(file,"| %s",ctime(&t));
You can use a combination of strftime()
and localtime()
to create a custom formatted string of your timestamp:
char s[1000];
time_t t = time(NULL);
struct tm * p = localtime(&t);
strftime(s, 1000, "%A, %B %d %Y", p);
printf("%s\n", s);
The format string used by ctime
is simply "%c\n"
.
You can use strtok()
to replace \n
with \0
. Here's a minimal working example:
#include <stdio.h>
#include <string.h>
#include <time.h>
int main() {
char *ctime_no_newline;
time_t tm = time(NULL);
ctime_no_newline = strtok(ctime(&tm), "\n");
printf("%s - [following text]\n", ctime_no_newline);
return 0;
}
Output:
Sat Jan 2 11:58:53 2016 - [following text]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With