这是我的代码
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <stdbool.h>
/*
Q: Read a log logfile, and parse each line into its constituent parts.
Each line contains a timestamp, log level, and message. The timestamp is enclosed in square brackets,
the log level is a single word, and the message may contain spaces.
input: 3 => size of log logfile
[2023-04-23 12:34:56] INFO Server started.
[2023-04-23 12:35:01] WARNING Request from 192.168.0.1 denied.
[2023-04-23 12:36:12] ERROR Database connection failed: Connection refused.
output: Timestamp: 2023-04-23 12:34:56
Log level: INFO
Message: Server started.
Timestamp: 2023-04-23 12:35:01
Log level: WARNING
Message: Request from 192.168.0.1 denied.
Timestamp: 2023-04-23 12:36:12
Log level: ERROR
Message: Database connection failed: Connection refused.
*/
typedef struct logfile
{
char *timestamp;
char *logLevel;
char *message;
struct logfile *next;
} logfile;
logfile *insertLoglogfile(logfile *info, char *timestamp, char *logLevel, char *message)
{
logfile *temp = malloc(sizeof(logfile));
temp->timestamp = timestamp;
temp->logLevel = logLevel;
temp->message = message;
temp->next = NULL;
if (info == NULL)
{
info = temp;
return info;
}
logfile *current = info;
while (current->next != NULL)
{
current = current->next;
}
current->next = temp;
return info;
}
void displayLoglogfile(logfile *info)
{
logfile *current = info;
while (current != NULL)
{
printf("\nTimestamp: %s\nLog level: %s\nMessage: %s\n", current->timestamp, current->logLevel, current->message);
current = current->next;
}
}
int main()
{
logfile *info = NULL;
char timestamp[20];
char logLevel[20];
char message[100];
int size;
scanf("%d", &size);
for (int i = 0; i < size; i++)
{
scanf("\n");
scanf("[%[^\]] %*c %s %[^\n]", timestamp, logLevel, message);
info = insertLoglogfile(info, timestamp, logLevel, message);
}
displayLoglogfile(info);
return 0;
}
我得到的输出为
`时间戳:2023-04-23 12:36:12日志级别:错误消息:数据库连接失败:连接被拒绝。
时间戳:2023-04-23 12:36:12日志级别:错误消息:数据库连接失败:连接被拒绝。
时间戳:2023-04-23 12:36:12日志级别:错误消息:数据库连接失败:连接被拒绝。”
它是存储在每个块的最后一个值,请帮助谢谢
1条答案
按热度按时间vmdwslir1#
你从main函数中引用
message
变量地址,因此你永远不会有一个副本。这同样适用于
timestamp
、level
以及从main传递到insert的任何内容,这些内容需要副本而不是引用。您需要在以下之前复制其内容:
完成后不要忘记释放通过
malloc
分配的内存。