You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

127 lines
3.4 KiB

#include "FileHandler.h"
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
#include <windows.h>
#include <direct.h>
#include <ctime>
#include <cstdio>
using namespace std;
void FileHandler::removeSpaces(string& str) {
str.erase(remove(str.begin(), str.end(), ' '), str.end());
}
string FileHandler::getBaseDirectory() {
return ".\\数学题目库";
}
void FileHandler::initializeBaseDirectory() {
string baseDir = getBaseDirectory();
// 检查基础目录是否存在
if (_access(baseDir.c_str(), 0) != 0) {
cout << "正在创建基础目录:" << baseDir << endl;
if (_mkdir(baseDir.c_str()) == 0) {
cout << "基础目录创建成功" << endl;
} else {
cout << "警告:无法创建基础目录" << endl;
}
}
}
string FileHandler::getCurrentTimeString() {
time_t now = time(nullptr);
tm* t = localtime(&now);
char timeStr[50];
sprintf(timeStr, "%04d-%02d-%02d-%02d-%02d-%02d",
t->tm_year + 1900, t->tm_mon + 1, t->tm_mday,
t->tm_hour, t->tm_min, t->tm_sec);
return string(timeStr);
}
bool FileHandler::createUserDirectory(const string& username) {
initializeBaseDirectory();
string dirPath = getBaseDirectory() + "\\" + username;
// 检查文件夹是否已存在
if (_access(dirPath.c_str(), 0) == 0) {
return false; // 文件夹已存在
}
// 创建新文件夹
if (_mkdir(dirPath.c_str()) == 0) {
return true; // 创建成功
} else {
return false; // 创建失败
}
}
void FileHandler::saveQuestionsToFile(const string& userType, int count,
const string& username, const string& questions) {
string timeStr = getCurrentTimeString();
string filename = timeStr + ".txt";
string filepath = getBaseDirectory() + "\\" + username + "\\" + filename;
// 打开文件进行写入
FILE* file = fopen(filepath.c_str(), "w");
if (file == NULL) {
printf("错误:无法创建文件 %s\n", filepath.c_str());
return;
}
// 写入文件头信息
fprintf(file, "用户:%s\n", username.c_str());
fprintf(file, "题目类型:%s\n", userType.c_str());
fprintf(file, "题目数量:%d\n", count);
fprintf(file, "生成时间:%s\n", timeStr.c_str());
fprintf(file, "============================\n\n");
// 写入题目内容
fprintf(file, "%s", questions.c_str());
fclose(file);
printf("题目已保存到文件:%s\n", filepath.c_str());
}
void FileHandler::clearInputBuffer() {
int c;
while ((c = getchar()) != '\n' && c != EOF);
}
void FileHandler::trimString(string& str) {
// 去除前导空格
size_t start = str.find_first_not_of(" \t\n\r");
if (start != string::npos) {
str = str.substr(start);
}
// 去除尾部空格
size_t end = str.find_last_not_of(" \t\n\r");
if (end != string::npos) {
str = str.substr(0, end + 1);
}
}
bool FileHandler::isNumber(const string& str) {
if (str.empty()) return false;
size_t start = 0;
if (str[0] == '-') {
start = 1;
if (str.length() == 1) return false;
}
for (size_t i = start; i < str.length(); i++) {
if (!isdigit(str[i])) {
return false;
}
}
return true;
}