0

我的 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(&current_time);
     strcat(time_string, activity);
     lf = fopen("logs.txt", "a+");
     fprintf(lf, "%s\n", activity);
     fclose(lf);
 }

该函数在 main 中调用,并为活动传递一个字符串文字。

4

4 回答 4

4

man ctime

该调用ctime(t)相当于asctime(localtime(t)). 它将日历时间转换为“Wed Jun 30 21:49:08 1993\n”t形式的以空字符结尾的字符串

所以一个\n字符包含在结果字符串中。您必须删除换行符:

char* nl = strrchr(time_string, '\n');
if (nl) *nl = '\0';

同样值得注意的是,来自同一个链接的参考页面:

返回值指向一个静态分配的字符串,随后调用任何日期和时间函数可能会覆盖该字符串。

由于所述原因strcat()这很重要,并且由于可能的缓冲区溢出,不知道该缓冲区有多大,因此将其用作 a 中的目标是不安全的。而不是执行strcat()删除换行符并执行两次文件写入;一个用于time_string,一个用于activity\n

于 2013-03-18T17:08:41.027 回答
1

返回的字符串ctime以换行符结尾。见ctime(3)

此外,您正在尝试修改ctime由 C 库使用的静态缓冲区返回的字符串。这可能导致缓冲区溢出。

于 2013-03-18T17:12:55.633 回答
1

怎么样

fprintf(lf, "%.*s %s\n", strlen(time_string) - 1, time_string, activity);

%.*s删除 time_string 的尾随换行符,因为指定的精度是字符串长度 - 1。

于 2013-03-18T17:20:53.643 回答
0
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(&current_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);
     }
 }
于 2013-03-18T17:44:31.650 回答