C++ 命令行阅读器:简单实现文本文件分页显示
以下是一个简单实现上述功能的 C++ 命令行阅读器的代码:
#include <iostream>
#include <fstream>
#include <string>
#include <conio.h>
#include <windows.h>
#define PAGE_SIZE 3000
void SetConsoleColor(WORD color) {
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, color);
}
void ClearConsole() {
COORD topLeft = {0, 0};
HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO screen;
DWORD written;
GetConsoleScreenBufferInfo(console, &screen);
FillConsoleOutputCharacterA(console, ' ', screen.dwSize.X * screen.dwSize.Y, topLeft, &written);
FillConsoleOutputAttribute(console, FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_RED,
screen.dwSize.X * screen.dwSize.Y, topLeft, &written);
SetConsoleCursorPosition(console, topLeft);
}
void PrintPage(const std::string& page, int pageNum) {
ClearConsole();
SetConsoleColor(FOREGROUND_INTENSITY | BACKGROUND_YELLOW);
std::cout << 'Page ' << pageNum << std::endl;
SetConsoleColor(FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
std::cout << page;
SetConsoleColor(FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
COORD pos = {0, 0};
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
}
std::string ReadFile(const std::string& filename) {
std::ifstream file(filename);
std::string content((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
return content;
}
int main() {
std::string filename = '1.txt';
std::string content = ReadFile(filename);
int totalPages = content.length() / PAGE_SIZE + 1;
int currentPage = 1;
std::string page = content.substr((currentPage - 1) * PAGE_SIZE, PAGE_SIZE);
PrintPage(page, currentPage);
while (true) {
int key = _getch();
if (key == 224) {
key = _getch();
if (key == 77) { // Right arrow key
if (currentPage < totalPages) {
currentPage++;
page = content.substr((currentPage - 1) * PAGE_SIZE, PAGE_SIZE);
PrintPage(page, currentPage);
}
} else if (key == 75) { // Left arrow key
if (currentPage > 1) {
currentPage--;
page = content.substr((currentPage - 1) * PAGE_SIZE, PAGE_SIZE);
PrintPage(page, currentPage);
}
}
}
}
return 0;
}
注意:上述代码中使用了 <conio.h> 头文件,这是一个非标准库,只在 Windows 平台上有效。如果你在其他平台上运行代码,可能需要使用其他库来处理键盘输入。此外,代码中使用了 Windows API 来设置命令行窗口的颜色和清空屏幕,因此在其他操作系统上可能无法正常工作。
原文地址: https://www.cveoy.top/t/topic/o7hk 著作权归作者所有。请勿转载和采集!