[英]How can I print the current date and time and a string to one line in a file in C?
我的C程序中有一个日志文件,我试图在每次用户执行查询时向其中输入条目。 它可以工作,除了将日期和时间打印到一行,将活动字符串打印到下面的行。 我需要将整个条目打印到一行。 我已经尝试了所有方法,但不明白为什么它不起作用。 我认为这与time_string有关。 请有人帮忙吗? 代码如下所示;
/*
* This function writes a log to the log file.
*/
void write_log(char *activity) {
FILE *lf;
time_t current_time;
char *time_string;
current_time = time(NULL);
time_string = ctime(¤t_time);
strcat(time_string, activity);
lf = fopen("logs.txt", "a+");
fprintf(lf, "%s\n", activity);
fclose(lf);
}
该函数在主体中调用,并为活动传递一个字符串文字。
从man ctime :
调用
ctime(t)
等效于asctime(localtime(t))
。 它将日历时间t
转换为以“ Wed Jun 30 21:49:08 1993 \\ n”形式的空终止字符串。
因此\\n
字符包含在结果字符串中。 您必须删除换行符:
char* nl = strrchr(time_string, '\n');
if (nl) *nl = '\0';
同样值得注意的是,来自同一链接的参考页面:
返回值指向静态分配的字符串,该字符串可能会被随后对任何日期和时间函数的调用所覆盖。
出于上述原因,这一点很重要, 并且未知该缓冲区的大小,因此由于可能的缓冲区溢出,将其用作strcat()
的目标是不安全的。 代替执行strcat()
删除换行符并执行两次写入文件; 一个用于time_string
,另一个用于activity\\n
。
ctime
返回的字符串以换行符结尾。 参见ctime(3)
。
另外,您正在尝试修改ctime
返回的字符串, ctime
是C库使用的静态缓冲区。 这可能导致缓冲区溢出。
怎么样
fprintf(lf, "%.*s %s\n", strlen(time_string) - 1, time_string, activity);
%.*s
将删除time_string的尾随换行符,因为指定的精度是字符串长度-1。
void write_log(char *activity)
{
FILE *lf;
time_t current_time;
char *time_string;
int length = 0;
char *line = NULL;
current_time = time(NULL);
time_string = ctime(¤t_time);
length = strlen(time_string) + strlen(activity) + 1;
line = (char *)malloc(length);
if(line){
memset(line,'\0',length);
strncpy(line,time_string, strlen(time_string)-1);
strcat(line," ");
strcat(line,activity);
lf = fopen("logs1.txt", "a+");
fprintf(lf, "%s\n", line);
fclose(lf);
free(line);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.