我在文本文件中插入时间时遇到问题。我使用下面的代码,我得到了|21,43,1,3,10,5| Wed Feb 01 20:42:32 2012,这是正常的,但我想做的是将时间放在数字之前,例如Wed Feb 01 20:42:32 2012 |21,43,1,3,10,5|,但是,当我在fprintf之前使用fprintf和ctime函数时,我不能这样做,因为它识别ctime内的\n数字,所以它更改了第一行,然后打印数字。它是这样的:
Wed Feb 01 20:42:32 2012
|21,43,1,3,10,5|这是我不想要的。如何在不切换到文本中的下一行的情况下打印时间?提前感谢!
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));发布于 2012-02-02 03:07:24
您可以组合使用strftime()和localtime()来创建您的时间戳的自定义格式化字符串:
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);ctime使用的格式字符串就是"%c\n"。
发布于 2015-12-29 23:21:40
只需使用%.19s:
struct timeb timebuf;
char *now;
ftime( &timebuf );
now = ctime( &timebuf.time );
/* Note that we're cutting "now" off after 19 characters to avoid the \n
that ctime() appends to the formatted time string. */
snprintf(tstring, 30, "%.19s", now); // Mon Jul 05 15:58:42发布于 2016-01-03 02:07:39
您可以使用strtok()将\n替换为\0。下面是一个最小的工作示例:
#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;
}输出:
Sat Jan 2 11:58:53 2016 - [following text]https://stackoverflow.com/questions/9101590
复制相似问题