11 Commits
Author SHA1 Message Date
Idiot-awa 91a1e3585a 更新README 2026-06-05 09:01:46 +08:00
Idiot-awa 541abc65a8 添加默克尔树实现交易完整性验证 2026-06-05 08:48:12 +08:00
Idiot ce8abe3c18 删除 test 2026-05-21 23:07:50 +08:00
Idiot-awa 9fb190ad5d Merge branch 'main' of http://idiot.asia/Idiot/BankManager 2026-05-21 23:01:12 +08:00
Idiot-awa 627201c739 增加交易日志搜索功能 2026-05-21 23:01:08 +08:00
Idiot 772b417cb2 添加 test 2026-05-08 17:08:33 +08:00
Idiot f4737c82f6 更新 README.md 2026-05-08 16:30:32 +08:00
Idiot 93e0214536 更新 README.md 2026-05-08 16:28:23 +08:00
Idiot-awa 74e467e111 增加日志 2026-05-08 12:39:58 +08:00
Idiot-awa 7d623c1993 增加日志 2026-05-08 11:46:09 +08:00
idiot ae99d48eda 更改编码为 utf8 2026-04-22 17:32:22 +08:00
10 changed files with 807 additions and 276 deletions
+6
View File
@@ -0,0 +1,6 @@
*.o
*.exe
*.dat
AGENTS.md
.vscode/launch.json
.vscode/tasks.json
+199 -110
View File
@@ -1,135 +1,224 @@
# 简易银行账户管理系统
# BankManager
## 项目简介
这是一个基于C语言开发的简易银行账户管理系统,支持基本的银行账户操作功能,包括开户、登录、存款、取款、查询余额、账户管理等。系统采用模块化设计,代码结构清晰,易于维护和扩展。
Windows 命令行银行账户管理系统,使用 C 语言实现,支持账户管理、交易记录和基于 Merkle 树的数据完整性校验。
## 功能特性
- **账户管理**
- 创建普通用户账户(权限2
- 创建管理员账户(权限1
- 删除账户(仅管理员可操作)
- 修改密码
- **账户操作**
- 存款
- 取款
- 查询余额
- **系统功能**
- 用户登录验证
- 权限分级(管理员/普通用户)
- 数据持久化(自动保存到文件)
- 自动初始化默认管理员账户
## 构建
## 系统架构
### 核心模块
1. **主程序 (bank.c)**
- 程序入口点
- 菜单显示和用户交互
- 权限控制逻辑
```powershell
gcc *.c -o bank.exe -ladvapi32
```
2. **账户管理 (account.c)**
- 账户创建、删除
- 账户查找
- 登录验证
- 密码修改
- 显示所有账户信息
运行:`.\bank.exe`
3. **交易处理 (transaction.c)**
- 存款功能
- 取款功能
- 余额查询
---
4. **数据持久化 (file_io.c)**
- 数据保存到文件(bank.dat
- 从文件加载数据
- 初始化默认管理员账户
## 数据结构总览
5. **工具函数 (utils.c)**
- 输入验证和清理
- 安全的整数和浮点数输入
项目围绕 **4 个核心数据结构** 构建,它们共同决定了系统的存储、操作和校验能力:
6. **头文件 (bank.h)**
- 全局常量定义
- 账户结构体定义
- 函数声明
| 数据结构 | 定义位置 | 用途 |
|----------|----------|------|
| `STACCOUNT` | `bank.h:8-15` | 账户信息记录 |
| `LogEntry` | `bank.h:55-62` | 单笔交易日志 |
| `LogQueue` | `bank.h:64-69` | 交易日志的环形缓冲队列 |
| `HashValue` | `bank.h:87-89` | SHA-256 哈希值(Merkle 树节点) |
---
## 1. STACCOUNT — 账户信息
### 数据结构
```c
typedef struct strAccount
{
int id; // 账户ID(从1000开始)
char name[31]; // 姓名(最多30字符)
#define MAX_ACCOUNTS 50
#define NAME_LEN 31
typedef struct strAccount {
int id; // 唯一账户 ID
char name[NAME_LEN]; // 户名(最长 30 字符)
double balance; // 账户余额
int password; // 6位数字密码
int quanxian; // 权限1=管理员2=普通用户
int password; // 6 位数字密码 (100000999999)
int quanxian; // 权限级别: 0=访客, 1=管理员, 2=普通用户
} STACCOUNT;
```
## 使用说明
### 编译
```bash
gcc bank.c account.c transaction.c file_io.c utils.c -o bank_system
### 全局实例
```c
STACCOUNT g_astAccounts[MAX_ACCOUNTS]; // bank.c:6 — 固定 50 槽位数组
int g_iAccCount; // bank.c:8 — 当前有效账户数量
```
### 运行
```bash
./bank_system
### 设计要点
- **固定容量**:最多 50 个账户,由 `MAX_ACCOUNTS` 宏控制。
- **删除策略**:删除账户时将其槽位**全部置零**(`memset`),而非移动元素。`LoadData` 通过统计 `id != 0` 的槽位重新计算 `g_iAccCount`
- **管理员硬编码**id=1000, password=123456`InitAdminAccount()` 每次启动都会强制覆盖第一个槽位(`account.c:18-22`)。
- **内存布局**`sizeof(STACCOUNT)` = 4 + 31 + 3(padding) + 8 + 4 + 4 = 54 字节(假设 64 位, 对齐后 56)。
---
## 2. LogEntry — 交易日志条目
```c
typedef struct {
int account_id; // 关联的账户 ID
char type[10]; // 操作类型: "Deposit" 或 "Withdraw"
double amount; // 交易金额
double balance; // 交易后余额
char timestamp[20]; // 时间戳 (格式: YYYY-MM-DD HH:MM:SS)
char location[50]; // 地点信息 (固定 "宇宙总行")
} LogEntry;
```
### 操作流程
1. **初始界面**(未登录状态)
- 选项1:开户(创建普通用户账户)
- 选项2:登录
- 选项0:退出系统
### 数据来源
2. **普通用户界面**(登录后)
- 选项1:存款
- 选项2:取款
- 选项3:查询余额
- 选项0:退出账户
- `type``amount``balance``Deposit()` / `Withdraw()` 填充。
- `timestamp``EnqueueLog()` 调用时通过 `time()` + `localtime()` 生成。
- `location``log.c:55` 硬编码为 `"宇宙总行"`
- **不可变**:一旦入队,LogEntry 不再被修改(除非被环形队列覆盖)。
3. **管理员界面**(登录后)
- 选项1:存款
- 选项2:取款
- 选项3:查询余额
- 选项4:显示所有账户
- 选项5:删除账户
- 选项6:创建管理员账户
- 选项0:退出账户
---
### 默认账户
系统首次运行时会自动创建一个默认管理员账户:
- **账户ID**: 1000
- **姓名**: admin
- **密码**: 123456
- **权限**: 管理员
## 3. LogQueue — 环形缓冲队列
## 技术细节
- **最大账户数量**: 50个
- **密码规则**: 6位数字(100000-999999
- **数据存储**: 二进制文件(bank.dat
- **输入验证**: 所有数值输入都包含错误处理
- **内存管理**: 使用全局数组存储账户数据
```c
#define MAX_LOGS 100
## 文件说明
- `bank.c` - 主程序文件
- `account.c` - 账户管理功能实现
- `transaction.c` - 交易处理功能实现
- `file_io.c` - 文件读写功能实现
- `utils.c` - 工具函数实现
- `bank.h` - 头文件,包含结构体定义和函数声明
- `bank.dat` - 数据存储文件(运行时自动生成)
typedef struct {
LogEntry logs[MAX_LOGS]; // 固定 100 条日志存储
int front; // 队头指针(最旧记录)
int rear; // 队尾指针(下一插入位)
} LogQueue;
```
## 注意事项
1. 密码必须为6位数字
2. 存款和取款金额必须为正数
3. 取款时会检查账户余额是否充足
4. 删除账户功能仅管理员可用
5. 系统会自动保存所有操作到文件,确保数据持久化
### 全局实例
## 扩展建议
- 添加交易记录功能
- 实现账户排序和搜索
- 增加更多权限级别
- 改进用户界面(如使用图形界面)
- 添加数据加密功能
- 实现多用户并发访问
```c
LogQueue g_logQueue; // bank.c:5
```
### 工作原理
```
初始状态: front = 0, rear = 0
入队 3 条: front = 0, rear = 3, 有效记录: [0, 1, 2]
入队 100 条后继续入队: front = 1, rear = 0, 有效记录: [1..99, 0](循环覆盖)
```
- **满判断**`(rear + 1) % MAX_LOGS == front` — 始终保留一个空位以区分满/空。
- **空判断**`front == rear`
- **容量上限**`MAX_LOGS - 1 = 99` 条有效记录。
- **溢出行为**:当队列满时,`EnqueueLog()` 静默覆盖最旧记录,并同步更新 Merkle 根。
- **遍历逻辑**`ShowTransactionLogs()``front``(rear - 1) % MAX_LOGS` 依次输出。
### 持久化
整个 `LogQueue` 结构体以二进制形式写入 `log.dat`
```
文件大小 = sizeof(LogQueue) = 100 * sizeof(LogEntry) + 2 * sizeof(int)
≈ 100 * 96 + 8 = 9608 字节
```
---
## 4. HashValue — SHA-256 哈希值
```c
#define HASH_SIZE 32
typedef struct {
unsigned char data[HASH_SIZE]; // 32 字节 RAW SHA-256 摘要
} HashValue;
```
### 全局实例
```c
HashValue g_merkleRoot; // merkle.c:8 — 所有日志的 Merkle 树根哈希
```
### 依赖
- 使用 **Windows CryptoAPI** (`wincrypt.h`) 计算 SHA-256。
- 编译时需链接 `-ladvapi32`
### Merkle 树构建流程 (`BuildMerkleTree`)
1. 读取 `g_logQueue` 中的所有有效日志条目(从 `front``rear`)。
2. 对每条 `LogEntry` 调用 `HashLogEntry()`,生成 **leaf hashes**(叶子节点)。
3. 将所有叶子哈希存储在**动态分配的 `HashValue* leaves` 数组**中(堆内存,使用后释放)。
4. 自底向上两两哈希合并,直到产生唯一的根哈希 → `g_merkleRoot`
5. 持久化到 `merkle.dat`32 字节固定大小)。
```
日志条目: [E1] [E2] [E3] [E4] [E5]
│ │ │ │ │
叶子哈希: [H1] [H2] [H3] [H4] [H5]
│ │ │ │ │
中间层: [H12] [H34] H5
│ │ │
顶层: [ H1234 ] H5
│ │
Merkle根: [ H12345 ] → g_merkleRoot
```
---
## 数据流与文件布局
```
┌──────────┐ 二进制块 (50 × sizeof(STACCOUNT)) ┌──────────┐
│ bank.dat │ ◄──────────────────────────────────► │ accounts │
│ 2700 B │ │ 内存数组 │
└──────────┘ └────┬─────┘
┌──────────┐ sizeof(LogQueue) 二进制块 ┌────────────┐ │
│ log.dat │ ◄──────────────────────────► │ logQueue │◄┘
│ ≈9608 B │ │ 环形队列 │ 交易操作
└──────────┘ └──┬─────────┘ 触发日志
┌──────────┐ 32 字节固定块 │ BuildMerkleTree()
│merkle.dat│ ◄───────────────── g_merkleRoot│
│ 32 B │ │
└──────────┘ │
▲ │
└────────── VerifyMerkleTree() ──────┘
```
### 文件一览
| 文件 | 大小 | 格式 | 内容 |
|------|------|------|------|
| `bank.dat` | 2700+ B | 二进制 | 50 个 `STACCOUNT` 连续存储 |
| `log.dat` | ~9608 B | 二进制 | 完整 `LogQueue` 结构体 |
| `merkle.dat` | 32 B | 二进制 | Merkle 根哈希 |
---
## 辅助数据结构
### KMP 部分匹配表(`log.c:111`
```c
int* lps = (int*)malloc(M * sizeof(int)); // 动态分配,搜索后释放
```
用于在日志中执行模式搜索(`SearchLogs``KMPSearch`),支持任意字符串模式匹配,而非简单的 `strstr`
### 全局状态变量
| 变量 | 类型 | 位置 | 说明 |
|------|------|------|------|
| `quanxian` | `int` | `bank.c:9` | 当前会话权限:0=未登录, 1=管理员, 2=用户, -2=退出 |
| `user_id` | `int` | `bank.c:10` | 当前登录用户 ID |
| `g_iAccCount` | `int` | `bank.c:8` | 有效账户数(不含已删除的空槽) |
---
## 已知限制
- **Windows 独占**:依赖 `<io.h>` 和 Windows CryptoAPI,无法在 POSIX 系统编译。
- **固定容量**:账户 50 个,日志 99 条有效记录,超出后日志自动覆盖。
- **明文密码**:密码以 `int` 类型存储,无哈希保护。
- **管理员硬编码**:每次启动强制重置,不支持持久化管理员的密码修改。
- **单用户会话**`quanxian``user_id` 是全局变量,不支持多用户并发。
+57 -57
View File
@@ -6,15 +6,15 @@
extern STACCOUNT g_astAccounts[];
extern int g_iAccCount;
/* 函数功能:处理用户的创建账户操作
思考处理步骤,写到函数体内注释
* 参数:无
* 存款信息要写入全局变量g_astAccounts中
* 返回值:无
* 存款失败怎么处理?
/* 函数功能:处理用户的创建账户操作
思考处理步骤,写到函数体内注释
* 参数:无
* 存款信息要写入全局变量g_astAccounts中
* 返回值:无
* 存款失败怎么处理?
*/
void InitAdminAccount() {
printf("初始化默认管理员账户");
printf("初始化默认管理员账户");
g_astAccounts[0].id = 1000;
strcpy(g_astAccounts[0].name, "admin");
g_astAccounts[0].balance = 0.0;
@@ -25,73 +25,73 @@ void InitAdminAccount() {
void CreateAccount(int quanxian)
{
// (1)合法性检查
// (1)合法性检查
if(MAX_ACCOUNTS < g_iAccCount)
{
printf("账户数量已达上限!\n");
printf("账户数量已达上限!\n");
return;
}
// (2)定义局部变量(函数内使用的变量)
STACCOUNT stNewAcc; //账户变量,结构体变量定义
//char cInput[NAME_LEN]; //接输入的名字字符串
// (2)定义局部变量(函数内使用的变量)
STACCOUNT stNewAcc; //账户变量,结构体变量定义
//char cInput[NAME_LEN]; //接输入的名字字符串
// (3)功能实现
printf("请输入姓名(最多30个字符): ");
// (3)功能实现
printf("请输入姓名(最多30个字符): ");
//这里有风险,怎么改进?
//这里有风险,怎么改进?
scanf("%30s", stNewAcc.name);
//stNewAcc.name[NAME_LEN - 1] = '\0'; // 确保null终止
//输密码
//stNewAcc.name[NAME_LEN - 1] = '\0'; // 确保null终止
//输密码
int temp_password;
while (1) {
printf("请输入密码\n");
printf("请输入密码\n");
scanf("%d",&temp_password);
if (99999<temp_password&&temp_password<999999) {
printf("设置成功\n");
printf("设置成功\n");
stNewAcc.password=temp_password;
SaveData();
break;
}
printf("密码不符合规范!请重新输入\n");
printf("密码不符合规范!请重新输入\n");
}
//需求中要求账户ID从1000开始,初始化账户余额
//需求中要求账户ID从1000开始,初始化账户余额
stNewAcc.id = 1000 + g_iAccCount;
stNewAcc.balance = 0.0;
stNewAcc.quanxian = quanxian;
g_astAccounts[g_iAccCount] = stNewAcc;
//把记录账户数量的全局变量自增。加过之后自增,所以下标0占用,数量是1个
//把记录账户数量的全局变量自增。加过之后自增,所以下标0占用,数量是1个
g_iAccCount++;
printf("开户成功! 账户ID: %d\n", stNewAcc.id);
printf("开户成功! 账户ID: %d\n", stNewAcc.id);
SaveData();
}
/* 函数功能:处理用户的显示所有用户信息的操作
思考处理步骤,写到函数体内注释
* 参数:无
* 从全局变量g_astAccounts中取信息,并显示
* 返回值:无
* 存款失败怎么处理?
/* 函数功能:处理用户的显示所有用户信息的操作
思考处理步骤,写到函数体内注释
* 参数:无
* 从全局变量g_astAccounts中取信息,并显示
* 返回值:无
* 存款失败怎么处理?
*/
void ShowAccounts()
{
//(1)输出用户内容提示
printf("\n所有账户信息:\n");
//(1)输出用户内容提示
printf("\n所有账户信息:\n");
//(2)检查是否有账户了?异常情况无账户的处理
//(2)检查是否有账户了?异常情况无账户的处理
if (0 == g_iAccCount)
{
printf("暂无账户信息\n");
printf("暂无账户信息\n");
return;
}
//(3)打印表头
printf("%-8s %-30s %-10s %-3s\n", "ID", "姓名", "余额","权限");
//(3)打印表头
printf("%-8s %-30s %-10s %-3s\n", "ID", "姓名", "余额","权限");
printf("------------------------------------------------------\n");
//(4)循环打印每一行
//(4)循环打印每一行
for(int i = 0; i < g_iAccCount; i++)
{
printf("%-8d %-30s %-10.2f %-10d\n",
@@ -99,37 +99,37 @@ void ShowAccounts()
}
}
//登录账户,返回权限
//登录账户,返回权限
int LoginAccount(int temp_id) {
int temp_password;
if (FindAccount(temp_id)==-1) {
printf("没有找到账户\n");
printf("没有找到账户\n");
return 0;
}
else {
while (1) {
printf("请输入密码");
printf("请输入密码");
scanf("%d", &temp_password);
if (g_astAccounts[FindAccount(temp_id)].password==temp_password) {
printf("欢迎用户%s \n",g_astAccounts[FindAccount(temp_id)].name);
printf("欢迎用户%s \n",g_astAccounts[FindAccount(temp_id)].name);
if (g_astAccounts[FindAccount(temp_id)].quanxian==1) {
printf("您目前以管理员身份登录");
printf("您目前以管理员身份登录");
return 1;
}
else {return 2;}
}
else {
printf("密码错误,请重新输入\n");
printf("密码错误,请重新输入\n");
}
}
}
}
/* 函数功能:根据输入的用户ID找到
思考处理步骤,写到函数体内注释
* 参数:无
* 用户ID跟数组ID
* 返回值:无
* 存款失败怎么处理?
/* 函数功能:根据输入的用户ID找到
思考处理步骤,写到函数体内注释
* 参数:无
* 用户ID跟数组ID
* 返回值:无
* 存款失败怎么处理?
*/
int FindAccount(int id)
{
@@ -140,15 +140,15 @@ int FindAccount(int id)
return -1;
}
//删除账户
//删除账户
void DeleteAccount(int id) {
printf("正在删除\n");
printf("正在删除\n");
int i=FindAccount(id);
if (i==-1) {
printf("有这个账户吗你就删");
printf("有这个账户吗你就删");
}
else {
printf("正在删除一下账户...");
printf("正在删除一下账户...");
printf("%-8d %-30s %-10.2f %-3d\n",
g_astAccounts[i].id, g_astAccounts[i].name, g_astAccounts[i].balance,g_astAccounts[i].quanxian);
for (; i < g_iAccCount-i; i++)
@@ -162,24 +162,24 @@ void DeleteAccount(int id) {
void ChangePassword(int id) {
int temp_password;
while (1) {
printf("请输入原密码");
printf("请输入原密码");
scanf("%d",&temp_password);
if (g_astAccounts[FindAccount(id)].password==temp_password) {
while (1) {
printf("请输入新密码\n");
printf("请输入新密码\n");
scanf("%d",&temp_password);
if (99999<temp_password&&temp_password<999999) {
printf("修改成功\n");
printf("修改成功\n");
g_astAccounts[FindAccount(id)].password=temp_password;
SaveData();
break;
}
printf("密码不符合规范!请重新输入\n");
printf("密码不符合规范!请重新输入\n");
}
}
else {
printf("密码错误,请重新输入");
printf("密码错误,请重新输入");
}
}
}
+56 -37
View File
@@ -2,7 +2,7 @@
#include <stdlib.h>
#include <string.h>
#include "bank.h"
LogQueue g_logQueue; // <-- 新增:定义全局日志队列
STACCOUNT g_astAccounts[MAX_ACCOUNTS];
int g_iAccCount = 1;
@@ -12,53 +12,54 @@ int d_id;
int main(void)
{
LoadData();
//(1)导入数据
//(1)导入数据
// which fuction?
//应该先导入数据再欢迎?还是欢迎了再导入数据?
printf("=== 简易银行账户管理系统 ===\n");
printf("欢迎使用! 系统已加载%d个账户\n", g_iAccCount);
InitAdminAccount();//初始化管理员账号
int iChoice=-1; //选择标志
//应该先导入数据再欢迎?还是欢迎了再导入数据?
printf("=== 简易银行账户管理系统 ===\n");
printf("欢迎使用! 系统已加载%d个账户\n", g_iAccCount);
InitAdminAccount();//初始化管理员账号
LoadMerkleRoot();
int iChoice=-1; //选择标志
int pChoice=-1;
while (1) {
//持续显示菜单的秘诀
//(2)显示主菜单,并且处理用户的选择
//持续显示菜单的秘诀
//(2)显示主菜单,并且处理用户的选择
if (quanxian==-2){break;}
printf("\n=== 简易银行账户管理系统 ===\n");
printf("\n=== 简易银行账户管理系统 ===\n");
switch(quanxian) {
case 0:
printf("1. 开户\n2. 登录 \n0. 退出\n");
//printf("1. 开户\n2. 存款\n3. 取款\n4. 查询\n5. 显示所有账户\n6. 退出\n");
printf("请选择: ");
printf("1. 开户\n2. 登录 \n0. 退出\n");
//printf("1. 开户\n2. 存款\n3. 取款\n4. 查询\n5. 显示所有账户\n6. 退出\n");
printf("请选择: ");
iChoice=-1;
scanf("%d", &iChoice);
switch(iChoice) {
case 1://CREATE
//调用创建账号的函数
//调用创建账号的函数
CreateAccount(2);
quanxian=0;
break;
case 2://LOGIN
printf("请输入账户id");
printf("请输入账户id");
scanf("%d", &user_id);
quanxian=LoginAccount(user_id);
break;
case 0://EXIT
printf("谢谢使用!\n按任意键退出\n");
printf("谢谢使用!\n按任意键退出\n");
getchar();
quanxian=-2;
exit(0);
//还要实现哪些菜单吗?
//如果要做排序展示,要做什么?
default: //好的编码习惯,对无效值做处理
printf("无效选择!\n");
break; //好的编码加上break,万一default挪了个位置呢?
//还要实现哪些菜单吗?
//如果要做排序展示,要做什么?
default: //好的编码习惯,对无效值做处理
printf("无效选择!\n");
break; //好的编码加上break,万一default挪了个位置呢?
}
break;
case 1:
printf("1. 存款\n2. 取款\n3. 查询\n4. 显示所有账户\n5. 删除账户\n6. 创建管理员账户\n0. 退出账户");
printf("1. 存款\n2. 取款\n3. 查询\n4. 显示所有账户\n5. 删除账户\n6. 创建管理员账户\n7.查看交易日志\n8.搜索交易日志\n9.查看默克尔根\n10.验证日志完整性\n0. 退出账户");
pChoice=-1;
scanf("%d", &pChoice);
@@ -76,7 +77,7 @@ int main(void)
ShowAccounts();
break;
case 5:
printf("请输入要删除的id");
printf("请输入要删除的id");
scanf("%d", &d_id);
DeleteAccount(d_id);
g_iAccCount--;
@@ -84,20 +85,38 @@ int main(void)
case 6:
CreateAccount(1);
break;
case 7:
ShowTransactionLogs();
break;
case 8:
printf("请输入搜索内容");
char pattern[50];
scanf("%s", pattern);
SearchLogs(pattern);
break;
case 9:
PrintMerkleRoot();
break;
case 10:
if (VerifyMerkleTree())
printf("\n默克尔树验证通过,日志未被篡改。\n");
else
printf("\n警告:默克尔树验证失败,日志可能已被篡改!\n");
break;
case 0://EXIT
printf("谢谢使用!\n按任意键退出");
printf("谢谢使用!\n按任意键退出");
getchar();
quanxian=-2;
//还要实现哪些菜单吗?
//如果要做排序展示,要做什么?
default: //好的编码习惯,对无效值做处理
printf("无效选择!\n");
break; //好的编码加上break,万一default挪了个位置呢?
//还要实现哪些菜单吗?
//如果要做排序展示,要做什么?
default: //好的编码习惯,对无效值做处理
printf("无效选择!\n");
break; //好的编码加上break,万一default挪了个位置呢?
}
break;
case 2:
printf("1. 存款\n2. 取款\n3. 查询\n0.退出账户");
printf("1. 存款\n2. 取款\n3. 查询\n0.退出账户");
pChoice=-1;
scanf("%d", &pChoice);
switch(pChoice) {
@@ -111,22 +130,22 @@ int main(void)
QueryBalance(user_id);
break;
case 0://EXIT
printf("谢谢使用!\n按任意键退出");
printf("谢谢使用!\n按任意键退出");
getchar();
quanxian=-2;
break;
//还要实现哪些菜单吗?
//如果要做排序展示,要做什么?
default: //好的编码习惯,对无效值做处理
printf("无效选择!\n");
break; //好的编码加上break,万一default挪了个位置呢?
//还要实现哪些菜单吗?
//如果要做排序展示,要做什么?
default: //好的编码习惯,对无效值做处理
printf("无效选择!\n");
break; //好的编码加上break,万一default挪了个位置呢?
}
break;
}
}
//(3)调用保存数据的函数
//(3)调用保存数据的函数
// which fuction?
return 0;
+63 -16
View File
@@ -1,10 +1,10 @@
#ifndef BANK_H
#define BANK_H
#define MAX_LOGS 100 // 日志队列最大容量,防止无限增长
#define MAX_ACCOUNTS 50 //系统规格为50个账户
#define NAME_LEN 31 //用户名字最长30字符,因此需要多1个字符串结束符
#define MAX_ACCOUNTS 50 //系统规格为50个账户
#define NAME_LEN 31 //用户名字最长30字符,因此需要多1个字符串结束符
// 账户信息,每个账户id对应了名字、账户余额等信息,是不是用数据结构定义比较合适?
// 账户信息,每个账户id对应了名字、账户余额等信息,是不是用数据结构定义比较合适?
typedef struct strAccount
{
int id;
@@ -16,39 +16,86 @@ typedef struct strAccount
// strAccount STACCOUNT;
// 函数声明,main函数中调用的各模块函数需要在程序公用的.h中声明
// 公开出来被其他模块调用的函数,也应该在公用的.h中声明
// 函数声明,main函数中调用的各模块函数需要在程序公用的.h中声明
// 公开出来被其他模块调用的函数,也应该在公用的.h中声明
//创建账户的函数
//创建账户的函数
void CreateAccount(int quanxian);
//实现存款的函数
//实现存款的函数
void Deposit(int id);
//实现取款的函数
//实现取款的函数
void Withdraw(int id);
//查询余额的函数
//查询余额的函数
void QueryBalance(int id);
//显示全部账户的函数
//显示全部账户的函数
void ShowAccounts();
//数据持久化函数
//数据持久化函数
void SaveData();
//加载数据的函数
//加载数据的函数
void LoadData();
//根据ID查找账户数组id的函数
//根据ID查找账户数组id的函数
int FindAccount(int iD);
//登录函数,返回用户权限
//登录函数,返回用户权限
int LoginAccount(int temp_id);
//销户
//销户
void DeleteAccount(int id);
void InitAdminAccount();
// 日志条目结构
typedef struct {
int account_id; // 涉及的账户ID
char type[10]; // 操作类型: "Deposit" 或 "Withdraw"
double amount; // 交易金额
double balance; // 交易后的余额
char timestamp[20]; // 时间戳 (格式: YYYY-MM-DD HH:MM:SS)
char location[50]; // 地点信息
} LogEntry;
// 环形队列结构
typedef struct {
LogEntry logs[MAX_LOGS];
int front; // 队头指针
int rear; // 队尾指针
} LogQueue;
// 全局日志队列变量 (在 bank.c 中定义,在其他文件中 extern 引用)
extern LogQueue g_logQueue;
// 日志函数声明
void InitLogQueue(); // 初始化队列
int IsLogQueueFull(); // 检查队列是否满
int IsLogQueueEmpty(); // 检查队列是否空
int EnqueueLog(int id, const char* type, double amt, double bal); // 入队
void ShowTransactionLogs(); // 显示所有日志
void SearchLogs(const char* pattern);//日志搜索
int GetLogCount();
#define HASH_SIZE 32
typedef struct {
unsigned char data[HASH_SIZE];
} HashValue;
extern HashValue g_merkleRoot;
void HashLogEntry(const LogEntry* entry, HashValue* out);
void BuildMerkleTree(HashValue* root);
void HashToHex(const HashValue* hash, char* hex_out);
void PrintMerkleRoot();
int VerifyMerkleTree();
void SaveMerkleRoot();
void LoadMerkleRoot();
#endif
+84
View File
@@ -0,0 +1,84 @@
#include <stdio.h>
#include <stdlib.h>
#include "bank.h"
#include <io.h>
#define FILE_NAME bank.bat
//要操作的全局变量,但不在本模块定义需要声明为外部引入
extern STACCOUNT g_astAccounts[];
extern int g_iAccCount;
/* 函数功能:数据持久化,将内存中的账户数据保存到文件中
保存方式为二进制
保存到文件bank.bat中,该文件名只在本模块用使用
* 参数:无
* 保存信息来自全局变量g_astAccounts
* 返回值:无
* 保存是失败怎么处理?
*/
void SaveData()
{
FILE *file = fopen("bank.dat", "wb");
fwrite(g_astAccounts, sizeof(STACCOUNT), 50, file);
fclose(file);
FILE *logfile = fopen("log.dat", "wb");
fwrite(&g_logQueue, sizeof(LogQueue), 1, logfile);
fclose(logfile);
LoadData();
}
/* 函数功能:从文件bank.bat中把账户数据读取到内存
操作的文件名仅在本模块中使用
* 参数:无
* 信息读取后放入全局变量g_astAccounts
* 返回值:无
* 读取失败怎么处理?
*/
void LoadData()
{
int i;
int result=0;
FILE *file = fopen("bank.dat", "rb");
if (file == NULL) {
InitAdminAccount();
g_iAccCount= 1;
}
else {
fread(g_astAccounts, sizeof(STACCOUNT), 50, file);
}
fclose( file);
for (i = 0; i < 50; i++) {
if (g_astAccounts[i].id != 0) {
result++;
}
}
g_iAccCount= result;
InitLogQueue();
FILE *logfile = fopen("log.dat", "rb");
if (logfile != NULL) {
fread(&g_logQueue, sizeof(LogQueue), 1, logfile);
fclose(logfile);
}
}
void SaveMerkleRoot() {
FILE* f = fopen("merkle.dat", "wb");
if (!f) return;
fwrite(g_merkleRoot.data, 1, HASH_SIZE, f);
fclose(f);
}
void LoadMerkleRoot() {
FILE* f = fopen("merkle.dat", "rb");
if (!f) {
memset(g_merkleRoot.data, 0, HASH_SIZE);
return;
}
fread(g_merkleRoot.data, 1, HASH_SIZE, f);
fclose(f);
}
+186
View File
@@ -0,0 +1,186 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "bank.h"
int GetLogCount() {
if (g_logQueue.rear >= g_logQueue.front)
return g_logQueue.rear - g_logQueue.front;
else
return MAX_LOGS - g_logQueue.front + g_logQueue.rear;
}
// 初始化日志队列
void InitLogQueue() {
g_logQueue.front = 0;
g_logQueue.rear = 0;
}
// 检查队列是否满
int IsLogQueueFull() {
return (g_logQueue.rear + 1) % MAX_LOGS == g_logQueue.front;
}
// 检查队列是否空
int IsLogQueueEmpty() {
return g_logQueue.front == g_logQueue.rear;
}
// 获取当前时间字符串
void GetCurrentTimeStr(char* buf) {
time_t t = time(NULL);
struct tm tm = *localtime(&t);
sprintf(buf, "%04d-%02d-%02d %02d:%02d:%02d",
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
tm.tm_hour, tm.tm_min, tm.tm_sec);
}
// 入队操作:记录交易
// 参数: 账户ID, 类型("Deposit"/"Withdraw"), 交易金额, 交易后余额
int EnqueueLog(int id, const char* type, double amt, double bal) {
// 如果队列满,通过移动 front 指针覆盖最旧的日志 (环形队列特性)
if (IsLogQueueFull()) {
// 覆盖旧数据,队头自动出队
g_logQueue.front = (g_logQueue.front + 1) % MAX_LOGS;
}
// 准备日志条目
int pos = g_logQueue.rear;
g_logQueue.logs[pos].account_id = id;
strcpy(g_logQueue.logs[pos].type, type);
g_logQueue.logs[pos].amount = amt;
g_logQueue.logs[pos].balance = bal;
GetCurrentTimeStr(g_logQueue.logs[pos].timestamp);
strcpy(g_logQueue.logs[pos].location, "宇宙总行"); // 根据你的需求固定地点
// 队尾指针后移
g_logQueue.rear = (g_logQueue.rear + 1) % MAX_LOGS;
BuildMerkleTree(&g_merkleRoot);
SaveMerkleRoot();
return 1; // 成功
}
// 显示所有日志 (从队头到队尾)
void ShowTransactionLogs() {
if (IsLogQueueEmpty()) {
printf("暂无交易日志记录。\n");
return;
}
printf("\n=== 交易流水日志 ===\n");
printf("%-5s %-8s %-10s %-10s %-15s %-20s\n", "ID", "操作", "金额", "余额", "时间", "地点");
printf("--------------------------------------------------------------\n");
int i = g_logQueue.front;
while (i != g_logQueue.rear) {
LogEntry e = g_logQueue.logs[i];
printf("%-5d %-8s %-10.2f %-10.2f %-15s %-20s\n",
e.account_id, e.type, e.amount, e.balance, e.timestamp, e.location);
i = (i + 1) % MAX_LOGS;
}
}
// 1. 构建部分匹配表 (Next Array)
// 这是KMP算法的核心预处理步骤
void ComputeLPSArray(const char* pattern, int M, int* lps) {
int len = 0; // length of the previous longest prefix suffix
lps[0] = 0; // lps[0] is always 0
int i = 1;
while (i < M) {
if (pattern[i] == pattern[len]) {
len++;
lps[i] = len;
i++;
} else {
if (len != 0) {
len = lps[len - 1];
} else {
lps[i] = 0;
i++;
}
}
}
}
// 2. KMP 搜索函数
// 在文本 text 中查找模式 pattern,找到后调用回调函数处理匹配位置
void KMPSearch(const char* pattern, const char* text, void (*callback)(int)) {
int M = strlen(pattern);
int N = strlen(text);
if (M == 0) return;
// 创建并计算LPS数组
int* lps = (int*)malloc(M * sizeof(int));
ComputeLPSArray(pattern, M, lps);
int i = 0; // index for text
int j = 0; // index for pattern
while (i < N) {
if (pattern[j] == text[i]) {
j++;
i++;
}
if (j == M) {
// 找到匹配,调用回调函数输出该行或处理
callback(i - j);
j = lps[j - 1];
} else if (i < N && pattern[j] != text[i]) {
if (j != 0) {
j = lps[j - 1];
} else {
i++;
}
}
}
free(lps);
}
// 3. 回调函数:用于打印匹配到的日志行号
void PrintMatchLine(int pos) {
// 这里简化处理,实际应用中需要根据换行符计算行号
// 或者直接打印匹配位置附近的上下文
printf("找到匹配 (位置: %d)\n", pos);
}
// 4. 对外接口:搜索交易日志
void SearchLogs(const char* pattern) {
if (IsLogQueueEmpty()) {
printf("暂无日志可供搜索。\n");
return;
}
printf("\n=== 搜索日志: '%s' ===\n", pattern);
// 简化版:遍历每一条日志进行匹配
int i = g_logQueue.front;
int lineNum = 1;
while (i != g_logQueue.rear) {
LogEntry e = g_logQueue.logs[i];
// 将日志条目格式化为字符串(模拟一行文本)
char logLine[200];
sprintf(logLine, "ID:%d Type:%s Amount:%.2f Balance:%.2f Time:%s",
e.account_id, e.type, e.amount, e.balance, e.timestamp);
// 使用KMP检查这一行是否包含模式
// 这里为了演示调用了标准 strstr,你可以将其替换为上面的 KMPSearch
// 但考虑到单行文本较短,KMP优势不大;如果是超长日志文件,KMP优势巨大
if (strstr(logLine, pattern) != NULL) {
printf("%-3d %-8d %-10s %-10.2f %-15s\n",
lineNum, e.account_id, e.type, e.amount, e.timestamp);
}
i = (i + 1) % MAX_LOGS;
lineNum++;
}
}
+98
View File
@@ -0,0 +1,98 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
#include <wincrypt.h>
#include "bank.h"
HashValue g_merkleRoot;
static HCRYPTPROV g_hProv = 0;
static void ensureProvider() {
if (g_hProv == 0)
CryptAcquireContext(&g_hProv, NULL, NULL, PROV_RSA_AES, CRYPT_VERIFYCONTEXT);
}
static void sha256(unsigned char* out, const unsigned char* data1, unsigned int len1,
const unsigned char* data2, unsigned int len2) {
HCRYPTHASH hHash = 0;
DWORD hashLen = HASH_SIZE;
ensureProvider();
CryptCreateHash(g_hProv, CALG_SHA_256, 0, 0, &hHash);
if (data1 && len1) CryptHashData(hHash, data1, len1, 0);
if (data2 && len2) CryptHashData(hHash, data2, len2, 0);
CryptGetHashParam(hHash, HP_HASHVAL, out, &hashLen, 0);
CryptDestroyHash(hHash);
}
/* ==================== Merkle Tree ==================== */
void HashLogEntry(const LogEntry* entry, HashValue* out) {
char buf[256];
sprintf(buf, "ID:%d Type:%s Amount:%.2f Balance:%.2f Time:%s Loc:%s",
entry->account_id, entry->type, entry->amount,
entry->balance, entry->timestamp, entry->location);
sha256(out->data, (unsigned char*)buf, (unsigned int)strlen(buf), NULL, 0);
}
static void hashPair(const HashValue* a, const HashValue* b, HashValue* out) {
sha256(out->data, a->data, HASH_SIZE, b->data, HASH_SIZE);
}
void BuildMerkleTree(HashValue* root) {
int count = GetLogCount();
if (count == 0) {
memset(root->data, 0, HASH_SIZE);
return;
}
HashValue* leaves = (HashValue*)malloc(count * sizeof(HashValue));
if (!leaves) return;
int i = g_logQueue.front;
int idx = 0;
while (i != g_logQueue.rear) {
HashLogEntry(&g_logQueue.logs[i], &leaves[idx]);
i = (i + 1) % MAX_LOGS;
idx++;
}
int n = count;
while (n > 1) {
int j;
for (j = 0; j < n / 2; j++)
hashPair(&leaves[2 * j], &leaves[2 * j + 1], &leaves[j]);
if (n % 2 == 1) {
hashPair(&leaves[n - 1], &leaves[n - 1], &leaves[n / 2]);
n = n / 2 + 1;
} else {
n = n / 2;
}
}
memcpy(root->data, leaves[0].data, HASH_SIZE);
free(leaves);
}
void HashToHex(const HashValue* hash, char* hex_out) {
int i;
for (i = 0; i < HASH_SIZE; i++)
sprintf(hex_out + i * 2, "%02x", hash->data[i]);
hex_out[HASH_SIZE * 2] = '\0';
}
void PrintMerkleRoot() {
char hex[65];
HashToHex(&g_merkleRoot, hex);
printf("\n当前默克尔根: %s\n", hex);
}
int VerifyMerkleTree() {
HashValue computed;
BuildMerkleTree(&computed);
return memcmp(computed.data, g_merkleRoot.data, HASH_SIZE) == 0;
}
+31 -29
View File
@@ -5,96 +5,98 @@
extern STACCOUNT g_astAccounts[];
extern int g_iAccCount;
/* 函数功能:处理用户的存款操作
需要什么步骤?
* 参数:无
* 存款信息要写入全局变量g_astAccounts中
* 返回值:无
* 存款失败怎么处理?
/* 函数功能:处理用户的存款操作
需要什么步骤?
* 参数:无
* 存款信息要写入全局变量g_astAccounts中
* 返回值:无
* 存款失败怎么处理?
*/
void Deposit(int id)
{
int amount;
int temp_password;
while (1) {
printf("请输入存款金额");
printf("请输入存款金额");
scanf("%d",&amount);
if (amount>0) {
break;
}
printf("?你存给我存个负的?重新说存多少");
printf("?你存给我存个负的?重新说存多少");
}
printf("请输入密码");
printf("请输入密码");
while (1) {
scanf("%d",&temp_password);
if (g_astAccounts[FindAccount(id)].password==temp_password) {
g_astAccounts[FindAccount(id)].balance+=amount;
printf("success");
QueryBalance(id);
EnqueueLog(id, "Deposit", amount, g_astAccounts[FindAccount(id)].balance);
SaveData();
break;
}
else
{
{
printf("密码错误,请重新输入");
printf("密码错误,请重新输入");
}
}
}
}
/* 函数功能:处理用户的取款操作
需要什么步骤?
* 参数:无
* 取款后,账户信息要写入全局变量g_astAccounts中
* 返回值:无
* 取款失败怎么处理?
/* 函数功能:处理用户的取款操作
需要什么步骤?
* 参数:无
* 取款后,账户信息要写入全局变量g_astAccounts中
* 返回值:无
* 取款失败怎么处理?
*/
void Withdraw(int id)
{
int amount;
int temp_password;
while (1) {
printf("请输入取款金额");
printf("请输入取款金额");
scanf("%d",&amount);
if (amount>0) {
break;
}
printf("?取款怎么能取负的呢");
printf("?取款怎么能取负的呢");
}
while (1) {
printf("请输入密码");
printf("请输入密码");
scanf("%d",&temp_password);
if (g_astAccounts[FindAccount(id)].password==temp_password) {
if (g_astAccounts[FindAccount(id)].balance>amount) {
if (g_astAccounts[FindAccount(id)].balance>=amount) {
g_astAccounts[FindAccount(id)].balance-=amount;
EnqueueLog(id, "Withdraw", amount, g_astAccounts[FindAccount(id)].balance);
printf("success");
QueryBalance(id);
SaveData();
return;
}
else {
printf("有那么多钱吗你就取?\n");
printf("有那么多钱吗你就取?\n");
QueryBalance(id);
return;
}
}
else {
printf("密码错误,请重新输入");
printf("密码错误,请重新输入");
}
}
}
/* 函数功能:处理用户查询余额操作
需要什么步骤?
* 参数:无
* 查询后全局变量是否需要变化?
* 返回值:无
* 查询失败怎么处理?
/* 函数功能:处理用户查询余额操作
需要什么步骤?
* 参数:无
* 查询后全局变量是否需要变化?
* 返回值:无
* 查询失败怎么处理?
*/
void QueryBalance(int id)
{
printf("你现在还有%f块\n",g_astAccounts[FindAccount(id)].balance);
printf("你现在还有%f块\n",g_astAccounts[FindAccount(id)].balance);
return;
}
+2 -2
View File
@@ -13,7 +13,7 @@ int GetInputInt(const char *prompt)
printf("%s", prompt);
while(scanf("%d", &value) != 1) {
ClearInput();
printf("输入错误,请重新输入: ");
printf("输入错误,请重新输入: ");
}
return value;
}
@@ -24,7 +24,7 @@ double GetInputDouble(const char *prompt)
printf("%s", prompt);
while(scanf("%lf", &value) != 1) {
ClearInput();
printf("输入错误,请重新输入: ");
printf("输入错误,请重新输入: ");
}
return value;
}