Bug*_*tGG 15 c printf file ctime text-files
我在文本文件中插入时间有问题.我使用下面的代码,我得到|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与ctimef函数之前fprintf它识别的数字\n在ctime内,因此它更改第1行然后打印数字.它像:
Wed Feb 01 20:42:32 2012
|21,43,1,3,10,5|
Run Code Online (Sandbox Code Playgroud)
这是我不想要的东西......我如何能够在没有切换到文本中的下一行的情况下缩短时间?提前致谢!
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));
Run Code Online (Sandbox Code Playgroud)
Ker*_* SB 25
您可以使用的组合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);
Run Code Online (Sandbox Code Playgroud)
使用的格式字符串ctime
很简单"%c\n"
.
小智 8
只需使用%.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
Run Code Online (Sandbox Code Playgroud)
在 C++11 中,你可以这样做:
#include <iostream>
#include <chrono>
#include <iomanip>
using namespace std;
using namespace chrono;
// Prints UTC timestamp
void printTime() {
time_point<system_clock> now = system_clock::now();
time_t now_time = system_clock::to_time_t(now);
auto gmt_time = gmtime(&now_time);
auto timestamp = std::put_time(gmt_time, "%Y-%m-%d %H:%M:%S");
cout << timestamp << endl;
}
Run Code Online (Sandbox Code Playgroud)
输出:
2017-06-05 00:31:49
您可以使用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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
Sat Jan 2 11:58:53 2016 - [following text]
Run Code Online (Sandbox Code Playgroud)