Hanoi(汉诺)塔问题

#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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值