#include <iostream>
#include <cstdlib>
#include <windows.h>
#include <string.h>
#define FILE_NAME "E:\\test_log.txt"
#define FILE_MAX_SIZE (1024*1024*1024)
#define TIME_PATTERN "%04u-%02u-%02u %02u:%02u:%02u.%03u " // 控制输出位数,不够左边补0
using namespace std;
void hanoi(int n, char one, char two, char three);
void move(char x, char y);
char *get_curr_time();
long get_file_size(char* filename);
void write_to_file(char* filename,long max_size, char* buffer, unsigned buf_size);
int main(void) {
int m;
printf("input the number of diskes: ");
scanf("%d", &m);
printf("The step to move %d diskes: \n", m);
hanoi(m, 'A', 'B', 'C');
return 0;
}
void hanoi(int n, char one, char two, char three) {
if (n == 1) {
move(one, three);
} else {
hanoi(n-1, one, three, two);
move(one, three);
hanoi(n-1, two, one, three);
}
}
void move(char x, char y) {
char buffer[32];
memset(buffer, 0, sizeof(buffer));
sprintf(buffer, "%c-->%c\n", x, y);
cout << buffer;
write_to_file(FILE_NAME, FILE_MAX_SIZE, buffer, strlen(buffer));
}
/*
* 写入日志文件
* @param filename: 日志文件名
* @param max_size: 日志文件大小限制
* @param buffer: 日志内容
* @param buf_size: 日志内容大小
* @return 空
*/
void write_to_file(char* filename, long max_size, char* buffer, unsigned buf_size) {
if (filename != NULL && buffer != NULL) {
// 文件超过最大限制, 删除
long length = get_file_size(filename);
if (length > max_size) {
unlink(filename); // 删除文件
}
// 写日志
FILE *fp = NULL;
fp = fopen(filename, "at+");
if (fp != NULL) {
char *curr_time = get_curr_time();
fwrite(curr_time, strlen(curr_time), 1, fp);
fwrite(buffer, buf_size, 1, fp);
fclose(fp);
fp = NULL;
}
}
}
/*
* 获得文件大小
* @param filename: 文件名
* @return 文件大小
*/
long get_file_size(char* filename) {
long length = 0;
FILE *fp = NULL;
fp = fopen(filename, "rb");
if (fp != NULL) {
fseek(fp, 0, SEEK_END);
length = ftell(fp);
}
if (fp != NULL) {
fclose(fp);
fp = NULL;
}
return length;
}
/* 获取系统当前时间,精确到毫秒 */
char *get_curr_time() {
SYSTEMTIME system_time;
GetLocalTime(&system_time);
char *curr_time = new char[25];
sprintf(curr_time, TIME_PATTERN,
system_time.wYear,
system_time.wMonth,
system_time.wDay,
system_time.wHour,
system_time.wMinute,
system_time.wSecond,
system_time.wMilliseconds);
return curr_time;
}