Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fprintf and ctime without passing \n from ctime

Tags:

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));
like image 607
BugShotGG Avatar asked Feb 01 '12 19:02

BugShotGG


2 Answers

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".

like image 151
Kerrek SB Avatar answered Oct 19 '22 15:10

Kerrek SB


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]
like image 45
MDMower Avatar answered Oct 19 '22 16:10

MDMower