[英]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.