C++ 命令行阅读器:分页显示文本文件
下面是一个使用 C++ 编写的命令行阅读器的示例代码,它可以分页显示文本文件,并支持使用方向键翻页。
#include <iostream>
#include <fstream>
#include <conio.h>
void setConsoleColor(int backgroundColor, int textColor) {
int color = (backgroundColor << 4) | textColor;
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color);
}
void displayPage(const std::string& pageContent, int pageNumber) {
system("cls");
setConsoleColor(14, 15); // 设置背景色为黄色,文字颜色为白色
std::cout << pageContent << std::endl;
setConsoleColor(0, 15); // 恢复默认颜色
std::cout << "\n\nPage: " << pageNumber << std::endl;
}
std::string loadPage(const std::string& fileName, int startChar, int numChars) {
std::ifstream file(fileName);
if (!file) {
std::cerr << "Failed to open file!" << std::endl;
exit(1);
}
std::string content;
int charCount = 0;
char ch;
while (file >> std::noskipws >> ch) {
if (charCount >= startChar && charCount < startChar + numChars) {
content += ch;
}
charCount++;
if (charCount >= startChar + numChars) {
break;
}
}
return content;
}
int main() {
const std::string fileName = "1.txt";
int startChar = 0;
int numChars = 3000;
int pageNumber = 1;
std::string pageContent = loadPage(fileName, startChar, numChars);
displayPage(pageContent, pageNumber);
while (true) {
int key = _getch();
if (key == 77) { // 右键
startChar += numChars;
pageNumber++;
pageContent = loadPage(fileName, startChar, numChars);
displayPage(pageContent, pageNumber);
} else if (key == 75) { // 左键
startChar -= numChars;
if (startChar < 0) {
startChar = 0;
}
pageNumber--;
pageContent = loadPage(fileName, startChar, numChars);
displayPage(pageContent, pageNumber);
}
}
return 0;
}
请注意,上述代码使用了 Windows 特定的 API 函数 SetConsoleTextAttribute 和 GetStdHandle,因此只能在 Windows 上运行。如果你使用的是其他操作系统,请根据相应的平台进行适当的修改。
原文地址: https://www.cveoy.top/t/topic/o7hg 著作权归作者所有。请勿转载和采集!